Java ExecutorService:我应该先使用lock来使用execute吗?

mat*_*boy 3 java multithreading thread-safety

我的课程安排如下:

public class MyClass {

   ExecutorService pool;

   public MyClass(){
     pool = ... //inited by a class that implements ExecutorService
   }

   public final void submit(Runnable run){
        pool.execute(run);
   }
}
Run Code Online (Sandbox Code Playgroud)

方法submit线程是安全的还是应该使用Lock基于系统的?例如

   ReentrantLock look  = new ReentrantLock();

   public final void submit(Runnable run){
        lock.lock();
        try{ pool.execute(run); } finally{lock.unlock();}
   }
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 8

不,在调用ExecutorService#submit时不需要锁定.

内存一致性效果:在向ExecutorService提交Runnable或Callable任务之前的线程中的操作发生在该任务执行的任何操作之前,而该操作又发生在通过Future.get()检索结果之前.

或者在调用Executor执行#execute:

内存一致性效果:在将Runnable对象提交给Executor之前,线程中的操作发生在执行开始之前,可能在另一个线程中.