小编Aki*_*rus的帖子

仅在添加到 HashSet 时进行同步是否是线程安全的?

想象有一个主线程,它创建一个 HashSet 并启动许多将 HashSet 传递给它们的工作线程。

就像下面的代码一样:

void main() {
  final Set<String> set = new HashSet<>();
  final ExecutorService threadExecutor = 
  Executors.newFixedThreadPool(10);

  threadExecutor.submit(() -> doJob(set));
} 

void doJob(final Set<String> pSet) {
  // do some stuff
  final String x = ... // doesn't matter how we received the value.
  if (!pSet.contains(x)) {
    synchronized (pSet) {
      // double check to prevent multiple adds within different threads
      if (!pSet.contains(x)) {
        // do some exclusive work with x.
        pSet.add(x);
      }
    }
  }
  // do some stuff …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading

5
推荐指数
1
解决办法
1081
查看次数

标签 统计

concurrency ×1

java ×1

multithreading ×1