Integer sum = futureTask.get(); 会等待其对应的线程执行完 ,即阻塞 再获得结果。
所以我在测试时,出现一个小插曲
@Slf4j
public class ThreeWays {
//1.自定义MyThread进行继承Thread
static void test001(){
Thread thread = new MyThread();
thread.setName("t1");
thread.start();
}
//2.实现Runnable接口
static void test002(){
Thread thread=new Thread(()-> {
for (int i = 0; i <1000 ; i++) {
log.info("{}",i);
}
});
thread.setName("t2");
thread.start();
}
//3.实现
static Integer test003() throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask=new FutureTask<>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int num=0;
for (int i = 0; i < 1000000; i++) {
num+=i;
log.info("{}",i);
}
return num;
}
});
Thread thread=new Thread(futureTask);
thread.start();
Integer sum = futureTask.get();
log.info("sum为:{}",sum);
return sum;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
// test001();
// test002();
test003();
log.info("123");
}
}
当使用Runable作为参数时 ,即 new Thread( runnable )
把runnable 赋给 target
再运行时,去判断,究竟是否调用 targert.run()
2.linux查看线程信息