【问题标题】:do ExecutorService and CountDownLatch block the main thread till they finish?ExecutorService 和 CountDownLatch 会阻塞主线程直到它们完成吗?
【发布时间】:2015-07-12 21:48:40
【问题描述】:

我的问题是,我有两个线程 t1 和 t2。他们都做了一些计算,根据我的程序,我想使用一种并发技术,阻塞直到 t1 和 t2 都完成它们的任务然后继续。

我尝试了countdownLatch,并阅读了ExecutorService 并做了一个小例子。关于ExecutorService,我做了以下事情:

executor.execute(new RunnableClass(bgr,3))
executor.execute(new RunnableClass(bgr,7))
executor.shutdown();

if (executor.isTerminated()) {
    print("terminated") 
}

并且从未打印过“终止”一词,这意味着executorService 对象不会阻塞。

请告诉我应该使用哪种并发技术来适应我的情况

【问题讨论】:

  • 认真阅读 API 文档。答案就在里面:docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
  • isTerminated() 不检查执行器是否已关闭,它会检查它是否已终止。正如 JB Nizet 所说,阅读文档,很清楚。如果您对文档有任何疑问,请告诉我们。
  • @m0skit0 我知道 isterminated() 不会检查执行程序是否已关闭..我想阻止直到 t1 和 t2 完成执行,以便我继续..请告知跨度>
  • 使用 awaitTermination,如 API 文档中所述。
  • 正如第一条评论中已经建议的那样:阅读文档。

标签: java multithreading executorservice countdownlatch


【解决方案1】:

在开始编码之前阅读文档总能弄清一些事情。 但只想分享几点: 1.) CountDownLatch 可以解决您的问题。在编码之前阅读此链接.. http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html 基本上这个概念是你已经将你的程序锁在一个固定的状态,并阻止它继续进行,直到锁被释放。 因此,您有 2 个线程...将 countdownlatch 值设置为 2。使两个线程在完成后递减该值。直到锁存器值递减到 0,主线程才会等待这发生。

executor.shutdown ....参考文档...它说它在关闭之前等待所有提交的任务完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-19
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多