gpt4 book ai didi

Java 执行器服务 : should I put a lock before to use execute?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:17 27 4
gpt4 key购买 nike

我有一个组织如下的类:

public class MyClass {

ExecutorService pool;

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

public final void submit(Runnable run){
pool.execute(run);
}
}

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

   ReentrantLock look  = new ReentrantLock();

public final void submit(Runnable run){
lock.lock();
try{ pool.execute(run); } finally{lock.unlock();}
}

最佳答案

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

Memory consistency effects: Actions in a thread prior to the submission of a Runnable or Callable task to an ExecutorService happen-before any actions taken by that task, which in turn happen-before the result is retrieved via Future.get().

或调用 Executor#execute 时:

Memory consistency effects: Actions in a thread prior to submitting a Runnable object to an Executor happen-before its execution begins, perhaps in another thread.

关于Java 执行器服务 : should I put a lock before to use execute?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16058419/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com