Java:同步 ExecutorService 有必要吗?

发布于 2024-12-20 21:34:56 字数 350 浏览 1 评论 0原文

我有一个包含可以在线程之间共享的 ExecutorService 的类:

class MyExecutor {
    ExecutorService e = Executors.newSingleThreadExecutor();
    ....
    .... 
    public void add(Runnable r) {
         e.executre(r);
    } 
}

是否有必要在 add 方法中同步 ExecutorService 对象,因为 add 方法可以从不同的线程调用或者 ExecutorService 线程安全吗?

I have a class containing an ExecutorService that can be shared between threads:

class MyExecutor {
    ExecutorService e = Executors.newSingleThreadExecutor();
    ....
    .... 
    public void add(Runnable r) {
         e.executre(r);
    } 
}

Is it necessary to synchronize the ExecutorService object in the add method since the add method can be called from differens threads or is the ExecutorService thread safe?

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

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

发布评论

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

评论(2

煮酒 2024-12-27 21:34:56

ExecutorService 必须使用线程安全队列(默认情况下)。这就是所需要的一切。

ExecutorService has to use a thread safe queue (Which it does by default). This is all that is needed.

我爱人 2024-12-27 21:34:56

不,不需要同步对 add() 方法的调用。

No, there is no need to synchronize calls to add() method.

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