Created 2 threads and called the join()
method on them. I was expecting the threads would run sequentially and give the desired result, but I am getting some random values in the result.
public class TestJoinMethod {
volatile private int count =0;
public static void main(String[] args) {
TestJoinMethod testJoinMethod = new TestJoinMethod();
testJoinMethod.execute();
}
public void execute() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10000; i++) {
count++;
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<10000; i++) {
count++;
}
}
});
t1.start();
t2.start();
try {
t1.join();
System.out.println(count);
t2.join();
System.out.println(count);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
Using the above code to get the value of count variable. As per my understanding the join()
method waits for the thread execution to be completed before the control of the calling thread goes to next statement. Expected result : sysout statement should print 10000 , 200000 respectively. However, the result is giving some random values : 14125 , 14125 or 16911, 16911.
Not able to understand why is this happening here, went through some tutorials also, but couldn't understand the exact issue here.
Appreciate your help here.