【JUC】02-FutureTask

1. Future

Future用于处理异步同时任务。FutureTask继承了RunnableFuture,可以使用Runnable和Callable进行初始化,下面为使用FutureTask的一个例子。

public class demo02 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 多线程、有返回值、异步任务

        // 定义参数为一个继承Runnable或Callable(有返回值、可抛异常)的FutureTask的类
        FutureTask<String> futureTask = new FutureTask<>(new MyThread());
        
        // 赋值给Thread
        Thread t1 = new Thread(futureTask, "t1");
        t1.start();
        
        // 通过FutureTask获取返回值
        String returnValue = futureTask.get();
        System.out.println(returnValue);
    }
}

class MyThread1 implements Runnable{
    // Runnable 无返回值,不会抛异常
    @Override
    public void run() {
    }
}

class MyThread implements Callable<String> {
    // Callable 有返回值,会抛异常
    @Override
    public String call() throws Exception {
        System.out.println("This is callable");
        return "Hello World";
    }
}

优点:future+ThreadPool异步多线程任务配合,能显著提高程序的执行效率。
缺点:

  • get()阻塞。方法容易阻塞主线程。一般将Future.get放在最后。
  • isDone()轮询。
    Future对于结果的获取不友好,只能通过阻塞或轮询的方式得到任务的结果。
public class demo03 {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(3);
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        FutureTask<String> futureTask = new FutureTask<>(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            latch.countDown();
            return "t1";
        });
        threadPool.submit(futureTask);
//        try {
//            // 等待超过3秒,抛出异常
//            System.out.println(futureTask.get(3, TimeUnit.SECONDS));
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } catch (ExecutionException e) {
//            throw new RuntimeException(e);
//        } catch (TimeoutException e) {
//            throw new RuntimeException(e);
//        }

        FutureTask<String> futureTask2 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            latch.countDown();
            return "t2";
        });
        threadPool.submit(futureTask2);

        FutureTask<String> futureTask3 = new FutureTask<>(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            latch.countDown();
            return "t3";
        });
        threadPool.submit(futureTask3);
        threadPool.shutdown();

        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        
        // isDone轮询
        while (true) {
            if(futureTask.isDone()) {
                try {
                    System.out.println(futureTask.get());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                }
                break;
            } else {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("cost time is " + (endTime - startTime) + " ms");
    }

    private static void func1() {
        long startTime = System.currentTimeMillis();
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            TimeUnit.MILLISECONDS.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            TimeUnit.MILLISECONDS.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("cost time is " + (endTime - startTime) + " ms");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CRE_MO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值