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.
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
synchronizedguarantees is that the block is run by 1 thread at a time.