硬核解析:Java线程-如何优雅地获取线程的执行结果

为什么要使用Future

线程获取到运行结果有几种方式

 

java

复制代码

public class Sum {  private Sum(){}  public static int sum(int n){    int sum = 0;    for (int i = 0; i < n; i++) {      sum += n;   }    return sum; } }

Thread.sleep()

 

java

复制代码

private static int sum_sleep = 0; Thread thread = new Thread(() -> sum_sleep = Sum.sum(100)); thread.start(); TimeUnit.SECONDS.sleep(1); System.out.printf("get result by thread.sleep: %d\n", sum_sleep);

使用sleep()方法获取,这种方法,有不可控性,也许sleep1秒钟,但是线程还没有执行完成,可能会导致获取到的结果不准确。

Thread.join()

 

java

复制代码

private static int sum_join = 0; Thread thread = new Thread(() -> sum_join = Sum.sum(100)); thread.start(); thread.join(); System.out.printf("get result by thread.join: %d\n", sum_join);

循环

 

java

复制代码

private static int sum_loop = 0; private static volatile boolean flag; ​ Thread thread = new Thread(() -> {  sum_loop = Sum.sum(100);  flag = true; }); thread.start(); int i = 0; while (!flag) {  i++; } System.out.printf("get result by loopLock: %d\n", sum_loop);

notifyAll() / wait()

 

java

复制代码

private static class NotifyAndWaitTest { ​    private Integer sum = null; ​    private synchronized void sum_wait_notify() {      sum = Sum.sum(100);      notifyAll();   } ​    private synchronized Integer getSum() {      while (sum == null) {        try {          wait();       } catch (Exception e) {          e.printStackTrace();       }     }      return sum;   } } private static void getResultByNotifyAndWait() throws Exception {    NotifyAndWaitTest test = new NotifyAndWaitTest();    new Thread(test::sum_wait_notify).start();    System.out.printf("get result by NotifyAndWait: %d\n", test.getSum()); }

Lock & Condition

 

java

复制代码

private static class LockAndConditionTest { ​    private Integer sum = null;    private final Lock lock = new ReentrantLock();    private final Condition condition = lock.newCondition(); ​    public void sum() {      try {        lock.lock();        sum = Sum.sum(100);        condition.signalAll();     } catch (Exception e) {        e.printStackTrace();     } finally {        lock.unlock();     }   } ​    public Integer getSum() {      try {        lock.lock();        while (Objects.isNull(sum)) {          try {            condition.await();         } catch (Exception e) {            throw new RuntimeException(e);         }       }     } catch (Exception e) {        e.printStackTrace();     } finally {        lock.unlock();     }      return sum;   } } ​ private static void getResultByLockAndCondition() throws Exception {  LockAndConditionTest test = new LockAndConditionTest();  new Thread(test::sum).start();  System.out.printf("get result by lock and condition: %d\n", test.getSum()); }

BlockingQueue

 

java

复制代码

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1); new Thread(() -> queue.offer(Sum.sum(100))).start(); System.out.printf("get result by blocking queue: %d\n", queue.take());

CountDownLatch

 

java

复制代码

private static int sum_countDownLatch = 0; ​ private static void getResultByCountDownLatch() {  CountDownLatch latch = new CountDownLatch(1); ​  new Thread(         () -> {            sum_countDownLatch = Sum.sum(100);            latch.countDown();         })     .start();  try {    latch.await(); } catch (Exception e) {    e.printStackTrace(); }  System.out.printf("get result by countDownLatch: %d\n", sum_countDownLatch); }

CyclicBarrier

 

java

复制代码

private static int sum_cyclicBarrier = 0; ​ private static void getResultByCycleBarrier() {  CyclicBarrier cyclicBarrier = new CyclicBarrier(2);  new Thread(   () -> {      sum_cyclicBarrier = Sum.sum(100);      try {        cyclicBarrier.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值