简体   繁体   中英

Unexpected output in multithreaded program

class ThreadSafe implements Runnable {
  int arr[]=new int[]{1,2,3,4,5};
  int sum=0;
  public void run() {
    int result=sum();
    System.out.println("for "+Thread.currentThread().getName()+"the value        is"+result);
  }

  public int sum() {
    for(int i=0;i<5;i++) {
      sum=sum+arr[i];
      System.out.println("calculating sum for      thread"+Thread.currentThread().getName()+"sum ="+sum);
      try {
        Thread.sleep(10);
      } catch(Exception e) {}
    }
    return sum;
  }

  public static void main(String...d) {
    ThreadSafe ts=new ThreadSafe();
    ThreadSafe ts1=new ThreadSafe();
    Thread t=new Thread(ts);
    Thread t1=new Thread(ts1);
    t1.start();
    t.start();
  }
}

I was expecting the output not to come 15. because the sum method is not synchronized so more then one thread can execute the sum method at the same time

What I was expecting that because the 2 thread's will execute the sum method instantly so the output should not be 15 because the first thread will update the value of sum to some value which will be read by the another thread.

So my question is why the output of the program come out the way I'm expecting even though i haven't synchronized the sum() method?

You're creating two instances of ThreadSafe , each with their own sum instance variable.

If you want them to overwrite each other (I'm assuming this is just playing around), create two Thread s on the same instance of ThreadSafe . Also, mark your sum variable as volatile to indicate that it can be changed by another thread (to avoid internal caching of the value if the compiler detects that it is not changed elsewhere within the method).

For example, change your main method to this:

public static void main(String...d) {
    ThreadSafe ts=new ThreadSafe();
    Thread t=new Thread(ts);
    Thread t1=new Thread(ts);
    t1.start();
    t.start();
  }

And the beginning of your ThreadSafe class definition to this:

class ThreadSafe implements Runnable {
  int arr[]=new int[]{1,2,3,4,5};
  volatile int sum=0;

Because you have two instances of ThreadSafe being handled by different threads. For producing your desired result it should be like one instance and multiple threads working on that same instance

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