【JUC】02-FutureTask

发布于:2024-08-08 ⋅ 阅读:(199) ⋅ 点赞:(0)

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");
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到