java callable 线程池 future

public class MyThread implements Callable<String> {

    private String name;
    private  int waittime;


    @Override
    public String call() throws Exception {

        log.info("mythread "+name+" start running" );
        if(waittime !=0)
            Thread.sleep(waittime);
        log.info("mythread "+name+" stop running" );
        return name;
    }
}

线程池

    static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
    
    @Test
    public void TestPollCallable(){
        List<MyThread> myThreadList = new ArrayList<>();
        for(int i=0;i<10;i++)
        {
            MyThread myThread = new MyThread("wait"+i,5000);
            myThreadList.add(myThread);
        }

        List <Future> futures = new ArrayList<>();

        myThreadList.stream().forEach(tr-> futures.add(fixedThreadPool.submit(tr)));

        futures.stream().forEach(future-> System.out.println("thread return "+future.get()));
    }

callable

    @Test
    public void  TestCallabe() throws ExecutionException, InterruptedException {
        MyThread myThread = new MyThread("wait10",3000); //
        FutureTask<String> result = new FutureTask<String>(myThread);
        new Thread(result).start();
        System.out.println("thread return"+ result.get());
    }

 线程池1

    static final ExecutorService THREAD_POOL= Executors.newFixedThreadPool(10);

    @Test
    public void contextLoads() throws ExecutionException, InterruptedException {

        FutureTask<String> resultaaatask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                log.info("start callablea");
                sleep(1000);
                return "hello aaa";
            }
        });

        FutureTask<String> resultbbbtask = new FutureTask<>(()->{
                log.info("start callableb");
                sleep(2000);
                return "hello bbb";
            }
        );

        THREAD_POOL.submit(resultaaatask);
        THREAD_POOL.submit(resultbbbtask);

        String retval =   resultaaatask.get();
        String retvalb = resultbbbtask.get();
        log.info("retval:"+retval+" "+retvalb);
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值