I am trying to create 5 different threads and try to print a static object in their run
method every time incrementing the count of static variable by one
Here is the sample output of the program
pool-1-thread-1 Static Value before update 19
Thread going to sleep pool-1-thread-1
pool-1-thread-4 Static Value before update 19
Thread going to sleep pool-1-thread-4
pool-1-thread-3 Static Value before update 19
Thread going to sleep pool-1-thread-3
pool-1-thread-2 Static Value before update 19
Thread going to sleep pool-1-thread-2
pool-1-thread-5 Static Value before update 19
Thread going to sleep pool-1-thread-5
Thread coming out of sleep pool-1-thread-3 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-4 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-1 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-5 StaticTest.sInt 19
Thread coming out of sleep pool-1-thread-2 StaticTest.sInt 19
**pool-1-thread-5 OLD value 22 Static Value after update 23**
pool-1-thread-1 OLD value 21 Static Value after update 22
pool-1-thread-4 OLD value 20 Static Value after update 21
pool-1-thread-3 OLD value 19 Static Value after update 20
pool-1-thread-2 OLD value 23 Static Value after update 24
Now my question is since Thread 3 came out of the sleep first it must have been printed first, however its thread 5 which is printed first and that too with value 22 i.e the static variable was incremented by three times before thread 5 gets hold of it, but why i see a random order while i am printing the incremented values to me it should have been printed in the same order the one they came out of sleep i.e thread 3/4/1/5/2
please pour in thoughts ? What I am missing why the random behaviour once the thread are back to running state after sleep
package com.test.concurrency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class StaticTest {
public static Integer sInt = new Integer(19);
public static void main(String[] args) {
ExecutorService es = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
es.execute(new StaticTask());
}
}
}
class StaticTask implements Runnable {
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name + " Static Value before update "
+ StaticTest.sInt);
try {
System.out.println("Thread going to sleep " + name);
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread coming out of sleep " + name + " StaticTest.sInt " + StaticTest.sInt);
int local = StaticTest.sInt;
StaticTest.sInt = new Integer(local + 1);
System.out.println(name + " OLD value " + local +" Static Value after update "
+ StaticTest.sInt);
}
}