JUC-Callable

2020-03-06  本文已影响0人  GIT提交不上

  FutureTask类图如下所示:(适配器模式)

图1-1 FutureTask类图.png

  Callable接口示例代码如下所示:

/**
 * @author luffy
 **/
public class CallableTest {
    public static void main(String[] args){

        FutureTask<Integer> task1 = new FutureTask<>(new ThreadTest());
        //FutureTask<Integer> task2 = new FutureTask<>(new ThreadTest()); 
        Thread t1 = new Thread(task1,"AA");
        Thread t2 = new Thread(task1,"BB");  //复用
        t1.start();
        t2.start();

        while (!task1.isDone()){
            
        }
        try {
            int res = task1.get();  //一般放在最后-要求获得Callable线程的结果,如果没有计算完则阻塞,直到计算完成
            System.out.println(res);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

    }
}
class ThreadTest implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+":come in!");
        return 1024;
    }
}
上一篇下一篇

猜你喜欢

热点阅读