创建线程的第三种方式:有返回值
Demo
package demo;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import static java.lang.System.out;
class MyThread2 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
TimeUnit.SECONDS.sleep(10);
out.println(Thread.currentThread().getName()+"********");
return 1024;
}
}
public class CallableDemo {
public static void main(String[] args) throws Exception {
FutureTask<Integer> integerFutureTask = new FutureTask<>(new MyThread2());
Thread aa = new Thread(integerFutureTask, "AA");
aa.start();
out.println(Thread.currentThread().getName()+"*******");
int result01=100;
int result02=0;
//如果阻塞时间过长加上这个
//isDone():执行结束(完成/取消/异常)返回true
while (!integerFutureTask.isDone()){
out.println("-------1");
TimeUnit.SECONDS.sleep(3);
}
//get():如果长时间未获取到结果会堵塞在这里
result02=integerFutureTask.get();
out.println("*******result: "+(result02+result01));
}
}
main*******
-------1
-------1
-------1
-------1
AA********
*******result: 1124
注意的点