当前位置: 移动技术网 > IT编程>开发语言>Java > Java CountDownLatch完成异步回调实例详解

Java CountDownLatch完成异步回调实例详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

cangzhou,泗水在线,富士施乐3200

java countdownlatch完成异步回调实例详解

实例代码:

public class asyncdemo {

  private static void dosometask() {
    system.out.println("hello world");
  }

  private static void oncompletion() {
    system.out.println("all tasks finished");
  }

  public static void main(string[] args) {
    executorservice executor = executors.newcachedthreadpool();
    final countdownlatch latch = new countdownlatch(2);

    executor.execute(new task(latch));
    executor.execute(new task(latch));

    executor.execute(() -> {
      try {
        latch.await();
      } catch (interruptedexception e) {
        e.printstacktrace();
      }
      oncompletion();
    });
    executor.shutdown();
  }

  private static class task implements runnable {

    /**
     * countdownlatch 是jdk提供的一个简单的线程监测工具
     * 基于简单的计数,调用countdown()方法表明当前线程已经终止
     * 在监测线程中调用await()方法,该方法会一直挂起直到所有其它线程终止
     */
    private final countdownlatch latch;

    public task(countdownlatch latch) {
      this.latch = latch;
    }

    @override
    public void run() {
      try {
        dosometask();
      } catch (exception e) {
        e.printstacktrace();
      } finally {
        latch.countdown();
      }
    }
  }
}

这里有两点需要补充:

1.如果你是用main方法启动的线程,这种调用方法是没有问题的,jdk会确保所有线程都终止以后main方法才退出。但是如果main方法不是异步任务的启动者(如junit,spring,tomcat),一旦启动之后laucher将会失去对线程的控制。如在junit中laucher提交完任务后就会被认为所有过程已完成,其它线程会被强行终止。

2.正因为如此,请根据环境使用正确的executor。比如,在web环境中,应该选用tomcat(或spring)管理的线程池作为executor,这样才能确保web应用对于异步任务的整个生命周期具有控制权;如果你选用jdk的线程池有什么后果呢?任务也许可以正常执行,当一旦你终止web-app,正在执行的异步线程并不会被正常kill掉,并由此造成内存泄漏或其它不可预见的后果。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网