简体   繁体   中英

Can someone explain this Java ThreadPool?

I've created a FixedThreadPool for a 1000 threads. Each individual thread needs to increment a global counter by one. So actually this is part of a programming assignment, I dont want the straight up answer, and i've already spend a few hours on this problem.

So some advice would be greatly appreciated. So this is my code :

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();
    }
}

The assignment specifically asks this : "Write a program that launches 1,000 threads. Each thread adds 1 to a variable sum that initially is 0. Define an Integer wrapper object to hold sum. Run the program with and without synchronization to see its effect. You can use newFixedThreadPool() to create a fixed number of threads in the pool. "

I've tried it already with a separate runnable taskClass for the threads. however I cant find a way to edit the sum variable from within the threads.

This inner thread way Im using now at least shows somewhat correct behaviour.

Could anyone provide some insights as to what would be a more correct way to adress such a problem ?

  • I am also unsure as to how and where implement the synchronization keyword to correctly force the threads to synchronize.

Kind regards! Sietze

For anyone interested I've come a solution from the author. I've its considered bad practice to post such solutions here I'll remove it.

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);
    }
  }
}

This solution seems to run correct result of 1000 without the synchronized keyword.

So would it make sense to implement the synchronized keyword here ? Personally I've placed it on the run method of the runnable class.

Anyway thanks all for response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM