• 多线程-Callable


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

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

    代码如下:

    
    
    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()+ " 执行完毕");

    }
    }
     

    结果如下:

    总结: 

    注意,当第二次调用futureTask2.get()方法时,会直接返回结果不会再等待做运算,要跟第一个做下区分
  • 相关阅读:
    查看SQL Server版本号(2005 & 2008)
    Installing an App for Testing
    Viewstate 的用法
    How to Open the Pdf file?
    工具类:Log
    SPSiteDataQuery and SPQuery
    SPSite, SPWeb Dispose and Class Design Partter
    Add Properties or Delete List Folder Content Type
    SharePoint UserControl
    Click Once 布署
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/15026146.html
Copyright © 2020-2023  润新知