java - 有人能解释一下这个Java线程池吗?

标签 java multithreading concurrency synchronization threadpool

我已经为 1000 个线程创建了一个固定线程池。 每个单独的线程都需要将全局计数器加一。 所以实际上这是编程作业的一部分,我不需要直接的答案,而且我已经在这个问题上花了几个小时。

因此,如果有一些建议,我们将不胜感激。这是我的代码:

public class ThreadSpawner {
private int sum = 0;
public static void main(String[] args){
    ThreadSpawner ts = new ThreadSpawner();
    ts.doWork();

}

public void doWork(){
    ExecutorService executor = Executors.newFixedThreadPool(1000);     
    for(int i =0;i<1000;i++){
        executor.execute(new Runnable(){

            @Override
            public void run() {
                System.out.println("Value: " + sum + Thread.currentThread());
                counter();
                }

            public synchronized void counter(){
                sum++;
            }
            });
        }
        executor.shutdown();
    }
}

作业特别要求:“编写一个启动 1,000 个线程的程序。每个线程将 1 添加到变量 sum 最初为 0。定义一个 Integer 包装对象来保存总和。运行程序有和没有 同步看看效果。 您可以使用 newFixedThreadPool() 在池中创建固定数量的线程。"

我已经尝试过使用线程的单独可运行任务类。但是我找不到从线程内编辑 sum 变量的方法。

我现在使用的这种内线程方式至少显示出一些正确的行为。

任何人都可以提供一些关于解决此类问题的更正确方法的见解吗?

  • 我也不确定如何以及在何处实现同步关键字以正确强制线程同步。

亲切的问候! 西泽

最佳答案

对于任何感兴趣的人,我从作者那里得到了一个解决方案。我认为在这里发布此类解决方案是不好的做法,我将删除它。

import java.util.concurrent.*;

public class Exercise30_04 {
  private int sum = new Integer(0);

  public static void main(String[] args) {
    Exercise30_04 test = new Exercise30_04();
    System.out.println("What is sum ? " + test.sum);
  }

  public Exercise30_04() {
    ExecutorService executor = Executors.newFixedThreadPool(1000);

    for (int i = 0; i < 1000; i++) {
      executor.execute(new SumTask());
    }

    executor.shutdown();

    while(!executor.isTerminated()) {
    }
  }

  class SumTask implements Runnable {
    public void run() {
      sum++;
//      int value = sum.intValue() + 1;
//      sum = new Integer(value);
    }
  }
}

这个解决方案似乎在没有同步关键字的情况下运行了 1000 的正确结果。

那么在这里实现synchronized关键字有意义吗? 就我个人而言,我将它放在可运行类的 run 方法上。

无论如何,感谢大家的回复。

关于java - 有人能解释一下这个Java线程池吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54422368/

相关文章:

java - EJB/JPA批处理异常管理

multithreading - C++原子内存顺序与线程事件,例如notify()

Python 多线程/多处理在 concurrent.futures 中非常慢

c# - 演示受限执行区域重要性的代码

java - 集合的并发映射 - 空时删除集合

java - 无法解析类型 org.eclipse.core.runtime.IConfigurationElement

java - 无法使用 4.x Android NFC API 推送 NdefMessage

java - 如何避免嵌套同步以及由此产生的死锁

java - 使用 Java 创建 Android 应用程序很困难

multithreading - Delphi-多线程端口检查器