Satya Jasti
Satya Jasti

Reputation: 49

Multithreading program output is not expected

multithreading

public class RaceData {

public static void main(String[] args) {

    class UnsafeSequence implements Runnable{
        private int value = 0;

        /** Returns a unique value. */

        public void run(){

            synchronized (this) {
                value = value +1;
                System.out.printf("Thread %s and Count value is %d \n",Thread.currentThread().getName(),value);
            }
        }
    }

    UnsafeSequence s = new UnsafeSequence();
    Thread t1 = new Thread(s);
    t1.setName("t1");
    t1.start();
    Thread t2 = new Thread(s);
    t2.setName("t2");
    t2.start();
    Thread t3 = new Thread(s);
    t3.setName("t3");
    t3.start();
    Thread t4 = new Thread(s);
    t4.setName("t4");
    t4.start();
    Thread t5 = new Thread(s);
    t5.setName("t5");
    t5.start();     
}
}

output is :

Thread t1 and Count value is 1 
Thread t5 and Count value is 2 
Thread t3 and Count value is 3 
Thread t4 and Count value is 4 
Thread t2 and Count value is 5 

Why count value is not getting displayed correctly ? sorry i am modifying my question it is not about count variable value, i expected thread t2 getting executed after t1 because i started t2 after t1, here threads are not executed in which they are ordered,though i started one after other.

Upvotes: 2

Views: 403

Answers (4)

Chander Shivdasani
Chander Shivdasani

Reputation: 10121

The order in which you start thread doesnt guarantee the way they will execute. Say, you started 3 threads, T1, T2, T3. Once you call T1.start(), T2.start() and T3.start(), all the threads move to a state called runnable which means, waiting for CPU to execute. CPU randomly selects any one of these threads and executes them. This is one of the perils of concurrent programming, that by default, the order of execution is random.

Upvotes: 1

Mitch
Mitch

Reputation: 1039

"value" is private to the class UnsafeSequence of which you only have a single instance. Every time run() is executed in the different threads, value is incremented and printed. The output is consistent with what I would expect.

Upvotes: 0

user684934
user684934

Reputation:

They're not executing in the order you're expecting because although the actual printing is done by a synchronized thread, there is no guarantee that the individual threads will arrive at the same time (and wait their turn).

All that the synchronized guarantees is that the block is run by 1 thread at a time.

Upvotes: 1

millhouse
millhouse

Reputation: 10007

The count is getting displayed correctly. Each time a thread gets access to the synchronized block, count gets incremented.

You cannot expect the threads to get access to the synchronized block in the same order that they were started.

Upvotes: 5

Related Questions