Java:同步 ExecutorService 有必要吗?
我有一个包含可以在线程之间共享的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
ExecutorService 必须使用线程安全队列(默认情况下)。这就是所需要的一切。
ExecutorService has to use a thread safe queue (Which it does by default). This is all that is needed.
不,不需要同步对 add() 方法的调用。
No, there is no need to synchronize calls to add() method.