0

I'm trying to run four threads. run() method has a for loop that loops 10 times.In each loop the shared resource "x" is increment by 1. When all threads die, the for loop should have run 4x10 =40 times and x value should equal 40.

That is not happening in all runs of the my code.Each time I run the code it prints a different value of x.Most of the output values of x range from 33 to 40.

Why is it not 40 in every run? Does that mean some for loop loops are being skipped? Is it caused due being blocked?

NOTE : this does not happen when sleep() is removed. It prints 40 every single time.

My code :

    public class MyThreadImplementsRunnable implements Runnable{

        int x =0;

        public void run() {

            for(int i=0;i<10;i++){
            x = x+1;

            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {

                System.out.println("exception");
                e.printStackTrace();
            }
            }
        }



        public static void main(String[] args) {

            MyThreadImplementsRunnable m = new MyThreadImplementsRunnable();
            Thread t1 = new Thread(m,"first");
            Thread t2= new Thread(m,"second");
            Thread t3= new Thread(m,"third");
            Thread t4= new Thread(m,"fourth");
            t1.start();
            t2.start();
            t3.start();
            t4.start();

            //To make sure not to go the next statement unless all threads die
            while(t1.isAlive()|| t2.isAlive()|| t3.isAlive()||t4.isAlive()){
            }

            //After all threads die
            System.out.println("now all threads are dead");
            //value of the shared resource x after all threads exit
            System.out.println(m.x);



        }

}

Some test runs gave the following results :

    Output:
    now all threads are dead
    34
    Output:
    now all threads are dead
    33
Sravani
  • 21
  • 4
  • 1
    Possible duplicate of [Make multiple threads use and change the same variable](https://stackoverflow.com/questions/14983847/make-multiple-threads-use-and-change-the-same-variable) –  Oct 09 '17 at 00:52
  • @Hugo - thanks for pointing it out.The answers for that questions helped.However, my question also is -"why it works fine and as expected when sleep() is not used? I guess this makes my question a little different. – Sravani Oct 09 '17 at 01:09

2 Answers2

0

x = x + 1 loads the value of x from memory, adds 1 to it and then stores it in x. Lets say Thread t1 loads 30 and at the same time thread t2 loads 30 they both increment 30 by 1 and store 31 in x instead of 32.

Why it's always 40 without sleep can be caused by many things I hypothesize that it's caused by each of the threads running very quickly and finishing before the next one starts.

You also don't use volatile and there are visibility issues but for now lets not get into that. This is also something you need to learn if you want to write multi-threaded code.

Oleg
  • 6,124
  • 2
  • 23
  • 40
0

You are using a shared resource(x) between threads which is bound to create many problems like data race, visibility.. Your answer will be always different

@oleg I don't think Volatile will help in this scenario

Neerav Vadodaria
  • 317
  • 1
  • 11
  • Neither do I. Even more then that I know it won't help. OP still needs to know about it and use it. It's like if you're going to drive your car of a cliff a seat belt is not going to help you, doesn't mean you shouldn't use a seat belt. I also don't know if you're aware of it but if you want me to see that you addressed me you need to either comment on my post or address my comment with @Oleg just typing in `@oleg` in your post is not going to do anything. – Oleg Oct 09 '17 at 15:17