多线程-Callable

 

1.FutureTask是Runnable接口的实现类,刚好构造器方法可以传入Callable.,然后就可以通过

new Thread(new FutureTask(new Callable())).start()类似方法创建线程执行,习惯使用lambda表达式。

多线程-Callable

多线程-Callable

 

 

多线程-Callable

代码如下:


class MyThread1 implements  Runnable {

@Override
public void run() {

}
}

class MyThread2 implements Callable<Integer> {

@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+" come in callable");
return 200;
}
}


public class CallableTest {
public static void main(String[ ]args) throws ExecutionException, InterruptedException {

// FutureTask<Integer> futureTask1 = new FutureTask<>(new MyThread2());
FutureTask<Integer> futureTask2 = new FutureTask<>(() -> {
System.out.println(Thread.currentThread().getName()+" come in callable");
return 1000;
});

// new Thread(new MyThread1(),"t1").start();
// new Thread(futureTask1,"t2").start();

new Thread(futureTask2,"t3").start();
while (!futureTask2.isDone()) {
System.out.println("wait-----");
}

// System.out.println(futureTask1.get());
System.out.println(futureTask2.get());
System.out.println(futureTask2.get());
System.out.println(Thread.currentThread().getName()+ " 执行完毕");

}
}
 

结果如下:

多线程-Callable

 

 

 

总结: 

注意,当第二次调用futureTask2.get()方法时,会直接返回结果不会再等待做运算,要跟第一个做下区分

 

上一篇:Callable、Runnable,Future和FutureTask之间关系


下一篇:线程池之Executor