public class Test1 {
public static void main(String[] args) {
//3. 创建Thread类的子类对象
MyThread myThread = new MyThread();
//4. 通过此对象调用start()方法
myThread.start();
}
}
//1. 创建一个继承于Thread类的子类
class MyThread extends Thread{
//2. 重写Thread类中的run()方法
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if(i % 2 == 0){
System.out.println(i);
}
}
}
}
public class Test2 {
public static void main(String[] args) {
//3. 创建实现类的对象
MyselfThread myselfThread = new MyselfThread();
//4. 将此对象作为参数传入到Thread类中的构造器中,创建Thread类的对象
Thread thread = new Thread(myselfThread);
//5. 通过Thread类的对象,调用start()
thread.start();
}
}
//1. 创建一个实现Runnable接口的类
class MyselfThread implements Runnable{
//2. 实现类去实现Runnable类中的run()方法
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if(i % 2 == 0){
System.out.println(i);
}
}
}
}
原因:
public class Test3 {
public static void main(String[] args) {
//3. 创建Callable接口实现类的对象
NumThread numThread = new NumThread();
//4. 将此Callable接口的实现类对象作为参数传递到FutureTask构造器中,创建FutureTask的对象
FutureTask futureTask = new FutureTask(numThread);
//5. 将FutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,并start()方法调用
Thread thread = new Thread(futureTask);
thread.start();
//6. 获取Callable中的call方法的返回值
try{
Object sum = futureTask.get();
System.out.println(sum);
}catch (InterruptedException e){
e.printStackTrace();
}catch (ExecutionException e){
e.printStackTrace();
}
}
}
//1. 创建一个实现Callable接口的实现类
class NumThread implements Callable{
//2. 实现call方法,将此线程需要执行的操作声明在call方法中
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i <= 100; i++) {
if(i % 2 == 0){
sum = sum + i;
}
}
return sum;
}
}
原文:https://www.cnblogs.com/CrabDumplings/p/13344487.html