Future Task

Future Task 属于并发类设计模式,简单理解就是在程序中开启多子线程去干一些事情,而我主线程继续干自己的事情,只是需要你子线程结果的时候,我找你拿就好了。

我需要你的结果的时候:

1)我可以先来问下你准本好没有,准备好了我就拿,如果没有准备好,我过一会儿再来问你。这个问和拿是两个分开的操作。

2)我也可以直接找你拿,你准备好了就直接给我,没有准备好,那我等你准备就是了。


代码示例:

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class FutureTaskTest {

    private static ExecutorService exec = Executors.newFixedThreadPool(2);

    public static void main(String args[]) throws InterruptedException, ExecutionException {

        FutureTask<String> future1 = new FutureTask<String>(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        Thread.sleep(new Random().nextInt(5000));
                        return "future1 success";
                    }
        });

        FutureTask<String> future2 = new FutureTask<String>(new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        Thread.sleep(new Random().nextInt(10000));
                        return "future2 success";
                    }
        });

        // 两个任务交给别人去执行
        exec.execute(future1);
        exec.execute(future2);

        // 我干我自己的事
        Thread.sleep(new Random().nextInt(1000));
        System.out.println("myself success");

        /** 先问,而且不停的问 */
        /*while(true){
            if(future1.isDone()){
                System.out.println(future1.get());
                break;
            }
            Thread.sleep(new Random().nextInt(1000));
        }*/

        // 我自己的事干完了,我需要你们的返回结果了
        System.out.println(future1.get());// 这个时候可能future1的数据还没有准备好,阻塞等待
        System.out.println(future2.get());// 这个时候可能future2的数据还没有准备好,阻塞等待

        exec.shutdown();

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值