Java executorService.awaitTermination()是否会阻止主线程并等待?

发布于 2025-02-11 04:22:19 字数 1058 浏览 2 评论 0原文

我已经进行了此测试代码:

    ExecutorService executor = Executors.newFixedThreadPool(3);
    executor.execute(new Runnable() {
      @Override
      public void run() {
        try {
          System.out.println("run begins");
          Thread.sleep(1000);
          System.out.println("run ends");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    try {
      executor.awaitTermination(0L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    executor.shutdown();
    System.out.println("-----------");

我希望,由于可运行的可运行应睡1秒然后结束,然后执行者等待其终止和关闭,最后,system.out.println(“ ----------------------------------) - ”);被执行。

但是真正的输出是:

-----------
run begins
run ends

执行顺序对我来说没有多大意义。似乎executorService.awaitxxx和shutdown()不会阻止主线程。 System.out.println(“ -----------”);是第一个打印的代码行,然后是可运行的代码。

这是设计的行为吗?

如果是,那么我的问题是:如果等待XXXX方法没有阻止主线程,那么主线程如何知道executorService完成?

I've this test code:

    ExecutorService executor = Executors.newFixedThreadPool(3);
    executor.execute(new Runnable() {
      @Override
      public void run() {
        try {
          System.out.println("run begins");
          Thread.sleep(1000);
          System.out.println("run ends");
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    try {
      executor.awaitTermination(0L, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    executor.shutdown();
    System.out.println("-----------");

I expected that, as the Runnable should sleep 1s and then ends, then executor await its termination and shutdown, finally, System.out.println("-----------"); is executed.

But the real output is:

-----------
run begins
run ends

The execution sequence doesn't make much sense to me. Seems the ExecutorService.awaitXXX and shutdown() doesn't block the main thread. The System.out.println("-----------"); was the first code line to print, and then the Runnable code.

Is this the designed behavior?

If yes, then my question is: if awaitXXXX method doesn't block the main thread, how does the main thread know when ExecutorService is done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我三岁 2025-02-18 04:22:19

似乎executorService.awaitxxx和shutdown()不会阻止
主线程

方法等待()确实 block 调用线程,但是您已经指定了0秒的超时。引用 javadoc

块,直到关闭请求或超时发生后所有任务都完成执行,或者当前线程被中断,以先到者为准。

如果您期望等待()将中断提交的任务,那么您的期望是错误的,那就不会了。此方法仅允许您指定等待期间并报告执行者是否完成的时间。

返回:
如果该执行人终止,则为false,如果终止之前的超时

超时

方法 shutdown() 也将 not> not 中断先前提交的任何任务:

启动有序的关机,在该关闭中,在该关闭中执行了先前提交的任务,但不会接受新任务。

如果您想尝试中断提交的任务,请使用 shutdownnow()

试图停止所有积极执行任务,停止处理任务的处理,并返回等待执行的任务列表。

注意:使用shutdown()是一种首选方法。

Seems the ExecutorService.awaitXXX and shutdown() doesn't block the
main thread

Method awaitTermination() does block the calling thread, but you've specified the timeout of 0 seconds. Quote from the javadoc:

Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

In case if you expected that awaitTermination() will interrupt submitted tasks, then your expectation is wrong, it wouldn't do that. This method only allows you to specify the period to wait and reports whether executor is done or not.

Returns:
true if this executor terminated and false if the timeout elapsed before termination

Method shutdown() also will not interrupt any tasks that are previously submitted:

Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.

If you wish to try to interrupt submitted tasks, use shutdownNow().

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

Note: usage of shutdown() is a preferred approach.

白芷 2025-02-18 04:22:19

来自 executorService#eekingtermination 的Javadocs:

块,直到所有任务完成执行 关闭请求

这意味着等待termination仅在关闭请求后才能使用,因此您需要调用shutdown() 等待()之前。

此外,AS @alexander ivanchenko 的另一个答案提到,设置了0L的超时将不等待任何东西,> code>> > >等待终止指示该线程是否通过返回值终止。如果您的主线程被另一个线程中断,则会抛出InterruptedException

From the Javadocs of ExecutorService#awaitTermination:

Blocks until all tasks have completed execution after a shutdown request

This means that awaitTermination will only work after a shutdown request so you need to call shutdown() before awaitTermination().

Furthermore, as the other answer by @Alexander Ivanchenko mentions, setting a timeout of 0L will not wait for anything and awaitTermination indicates whether the thread terminated in time via a return value. The InterruptedException is thrown if your main thread is interrupted by another thread.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文