futuretask


import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * Created by yuzhimin
 */
public class FutureTest {
    public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        Callable<String> callable = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(3000);
                return "aaa";
            }
        };

        FutureTask<String> futureTask = new FutureTask<>(callable);
        new Thread(futureTask).start();

        try {
            Thread.sleep(2000);
        } catch (Exception e) {
        }

        if (futureTask.isDone()) {
            System.out.println("futuretask done");
        } else {
            System.out.println("futuretask not done");
        }

        System.out.println("1221");

        try {
            System.out.println("child thread value:"+futureTask.get());
        } catch (Exception e) {
        }

        System.out.println("总耗时:"+(System.currentTimeMillis()-startTime));
    }
}


import java.util.concurrent.*;

/**
 * Created by yuzhimin
 */
public class ExecutorCompletionTest {

    static String doSomething(String somebody,long sleepTimestamp){
        try {
            Thread.sleep(sleepTimestamp);
        } catch (Exception e){
        }

        return somebody;
    }

    public static void main(String[] args) {
        long starttime = System.currentTimeMillis();
        ExecutorService executor = Executors.newCachedThreadPool();
        ExecutorCompletionService<String> completionService = new ExecutorCompletionService<>(executor);

        completionService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                return doSomething("B",8000);
            }

        });

        completionService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                // TODO Auto-generated method stub
                return doSomething("A",4000);
            }
        });

        int threadsize = 2;

        for (int i = 0; i < threadsize; i++) {
            try {
                Future<String> future = completionService.take();
                String result = future.get();
                System.out.println(result+"总耗时:"+(System.currentTimeMillis()-starttime));
            } catch (Exception e) {

            }
        }
        System.out.println("all耗时:"+(System.currentTimeMillis()-starttime));
        executor.shutdown();
    }
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值