Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make multiple threads use and change the same variable

in my program I need to have multiple threads use and edit the same variable, but it doesn't seem to be working. Here is an example of what I mean, this would be my main class.

public class MainClass {

  public static int number = 0;
  public static String num = Integer.toString(number);

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of threads.");
    int threads = in.nextInt();
    for (int n = 1; n <= threads; n++) {
      java.lang.Thread t = new Thread();
      t.start();
    }
  }
}

This would be my Thread class:

public class Thread extends java.lang.Thread
{
  public void run()
  {
      MainClass.number++;
      System.out.println("Thread started");
      System.out.println(MainClass.num);
  }
}

I wrote this code on the spot, so there may be some errors, but thats ok. My program basically needs to do something like this, but instead of printing the number plus 1 every time, all the threads simply print the same number, 0, multiple times. Please help me, thanks.

like image 815
user1947236 Avatar asked Dec 26 '22 09:12

user1947236


1 Answers

In my program I need to have multiple threads use and edit the same variable, but it doesn't seem to be working...

Anytime multiple threads are updating the same variable you need to worry about memory synchronization. One of the ways that threads get high performance is because each thread utilizes the local CPU memory cache and so may be working with stale copies of variables. You need to use the synchronized or volatile keywords to force the thread's cache to write any updates to central storage or update its cache from central.

Although this takes care of memory synchronization, it doesn't necessarily protect you from race conditions. It is also important to realize that ++ is actually 3 operations: get the current value, increment it, and store it back again. If multiple threads are trying to do this, there are thread race-conditions which can cause the ++ operations to be missed.

In this case, you should use the AtomicInteger class which wraps a volatile int field. It gives you methods like incrementAndGet() which do the job of incrementing that field in a thread-safe manner.

public static AtomicInteger number = new AtomicInteger(0);
...
MainClass.number.incrementAndGet();

Multiple threads can then be incrementing the same variable safely.

like image 87
Gray Avatar answered Dec 28 '22 22:12

Gray