1.Thread类,单继承的方式得到线程子类,定死了结构方法.
class MyThread extends Thread{
@override
run(){
}
}
2.Runnable接口,灵活,真正体现了多线程共享数据的模式。
new Runnable(){
@override
run(){
}
};
3.Callable 接口,java.util.concurrent.FutrueTask
class ThreadDemo implments Callable<Integer>{
@Overrid
public Integer call(){
int num = 0;
for(int i=o;i<100;i++){
num+=num+i;
return num;
}
}
}
public class TestCallable {
public static void main(String[] args) {
ThreadDemo td = new ThreadDemo();
//1.执行 Callable 方式,需要 FutureTask 实现类的支持,用于接收运算结果。
FutureTask<Integer> result = new FutureTask<>(td);
new Thread(result).start();
//2.接收线程运算后的结果
try {
Integer sum = result.get(); //FutureTask 可用于 闭锁 类似于CountDownLatch的作用,在所有的线程没有执行完成之后这里是不会执行的
System.out.println(sum);
System.out.println("------------------------------------");
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}