java JUC里的FutureTask类的两种简单用法

第一种使用public FutureTask(Runnable runnable, V result)这个构造函数

@Slf4j
public class FutureTaskExample1 {
    private static String result="no Done";
    public static void main(String[] args) throws Exception {
        FutureTask<String> futureTask = new FutureTask<>(new Runnable() {
            @Override
            public void run() {
                result="Done";
                log.info("do someThing in Runnable");
            }
        },result);
        log.info("do someThing in main");
        log.info("result:{}", result);
        new Thread(futureTask).start();
        Thread.sleep(1000);
        log.info("result:{}", result);
    }
}

 

第二种使用public FutureTask(Callable<V> callable)构造函数

@Slf4j
public class FutureTaskExample {

    public static void main(String[] args) throws Exception {
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("do someThing in Callable");
                return "Done";
            }
        });
        new Thread(futureTask).start();
        log.info("do someThing in main");
        Thread.sleep(1000);
        String result = futureTask.get();
        log.info("result:{}", result);
    }
}
    原文作者:JUC
    原文地址: https://blog.csdn.net/qq_38522268/article/details/84955338
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞