美文网首页
JUC-Callable

JUC-Callable

作者: GIT提交不上 | 来源:发表于2020-03-06 10:51 被阅读0次

  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;
    }
}

相关文章

  • JUC-Callable

      FutureTask类图如下所示:(适配器模式)   Callable接口示例代码如下所示:

网友评论

      本文标题:JUC-Callable

      本文链接:https://www.haomeiwen.com/subject/svdvrhtx.html