线程的第三种创建方式
Callable的使用
public class MyThread implements Callable {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+ ":11111111");
return 1024;
}
}
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask<>(new MyThread());
Thread thread = new Thread(futureTask,"AAA");
thread.start();
System.out.println(futureTask.get());
}
}
AAA:11111111
1024
futureTask.get()建议放在代码的最后面,否则main线程会等待子线程执行完才会执行。
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
Thread thread = new Thread(futureTask,"AAA");
thread.start();
System.out.println(Thread.currentThread().getName()+"*********");
int a = 1000;
while (!futureTask.isDone()){
System.out.println("未完成");
}
System.out.println("------------------------完成");
int number = futureTask.get();
System.out.println(a+number);
}
}
可以加个 while (!futureTask.isDone()){}应用
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
new Thread(futureTask,"AAA").start();
new Thread(futureTask,"BBB").start();
System.out.println(Thread.currentThread().getName()+"*********");
int a = 1000;
int number = futureTask.get();
System.out.println(a+number);
}
}
结果:
main*********
AAA:11111111
2024
总结:
两个线程调用同一个任务,只会打印一次,AAA线程或者BBB线程进入。
除非申请两个不通的任务,就是调用两次
FutureTask<Integer> futureTask2 = new FutureTask<>(new MyThread());
new Thread(futureTask2,"BBB").start();