java Future功能介绍

给一个Future的简单例子:

import java.util.concurrent.*;
public class FutureUsage {

    private ExecutorService executor
            = Executors.newSingleThreadExecutor();
    //创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
    public Future<Integer> calculate(Integer input) {
        return executor.submit(() -> {
            System.out.println("Calculating..."+ input);
            Thread.sleep(1000);
            return input * input;
        });
    }
    //这里调用submit方法,该方法接收Runnable或Callable对象作为输入参数

    public void shutDown(){
        executor.shutdown();
    }

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

        FutureUsage futureUsage=new FutureUsage();
        Future<Integer> futureOne = futureUsage.calculate(20);
        while(!futureOne.isDone()) {
            System.out.println("Calculating...");
            Thread.sleep(300);
        }
        Integer result = futureOne.get();
        System.out.println("futureOne return value is " + result);

        Future<Integer> futureTwo = futureUsage.calculate(4);

        boolean canceled = futureTwo.cancel(true);
        //调用cancel停止该任务,若成功返回true,若失败返回false。


        Future<Integer> future1 = futureUsage.calculate(10);
        Future<Integer> future2 = futureUsage.calculate(100);

        while (!(future1.isDone() && future2.isDone())) {
            System.out.println(
                    String.format(
                            "future1 is %s and future2 is %s",
                            future1.isDone() ? "done" : "not done",
                            future2.isDone() ? "done" : "not done"
                    )
            );
            Thread.sleep(300);
        }
        //isDone接口判断任务是否完成。
        Integer result1 = future1.get();
        Integer result2 = future2.get();

        System.out.println(result1 + " and " + result2);

        futureUsage.shutDown();
        //关闭线程池。

    }
}

输出结果:

Calculating...
Calculating...20
Calculating...
Calculating...
Calculating...
futureOne return value is 400
Calculating...10
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
future1 is not done and future2 is not done
Calculating...100
future1 is done and future2 is not done
future1 is done and future2 is not done
future1 is done and future2 is not done
100 and 10000

Future的原理是异步执行,开启多线程后,主线程可以先做其他的事情,等待一段时间后,再去查询是否执行完成,若完成则可以获取结果。

这里需要注意Future.get的方法是阻塞的,如果未完成将一直等待,可以使用带参数的get(long, TimeUnit)来确保一定时间后返回,同样给出代码:

import java.util.concurrent.*;
public class FutureUsage {

    private ExecutorService executor
            = Executors.newSingleThreadExecutor();
    //创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
    public Future<Integer> calculate(Integer input) {
        return executor.submit(() -> {
            System.out.println("Calculating..."+ input);
            Thread.sleep(500);
            return input * input;
        });
    }
    //这里调用submit方法,该方法接收Runnable或Callable对象作为输入参数

    public void shutDown(){
        executor.shutdown();
    }

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

        FutureUsage futureUsage=new FutureUsage();
        Future<Integer> futureOne = futureUsage.calculate(20);
        while(!futureOne.isDone()) {
            System.out.println("Calculating...");
            Thread.sleep(300);
        }
        Integer result = futureOne.get();
        System.out.println("futureOne return value is " + result);

        Future<Integer> futureTwo = futureUsage.calculate(4);

        boolean canceled = futureTwo.cancel(true);
        //调用cancel停止该任务,若成功返回true,若失败返回false。


        Future<Integer> future1 = futureUsage.calculate(10);
        Future<Integer> future2 = futureUsage.calculate(100);

        while (!(future1.isDone() && future2.isDone())) {
            System.out.println(
                    String.format(
                            "future1 is %s and future2 is %s",
                            future1.isDone() ? "done" : "not done",
                            future2.isDone() ? "done" : "not done"                           
                    )
            );
            Integer tmpResult = null;
            try {
                tmpResult = future2.get(50,TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                
            }               
            if(tmpResult != null) {
                System.out.println("tmpResult: " + tmpResult);
            } else {
                System.out.println("tmpResult is null.");
            }
            Thread.sleep(30);
        }
        //isDone接口判断任务是否完成。
        Integer result1 = future1.get();
        Integer result2 = future2.get();

        System.out.println(result1 + " and " + result2);

        futureUsage.shutDown();
        //关闭线程池。

    }
}

输出结果:

Calculating...
Calculating...20
Calculating...
futureOne return value is 400
Calculating...10
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
tmpResult is null.
future1 is not done and future2 is not done
Calculating...100
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult is null.
future1 is done and future2 is not done
tmpResult: 10000
100 and 10000

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值