I have this piece of code using Java Thread:
public class ThreadExample implements Runnable{
public Thread thread;
static int i = 0;
ThreadExample(){
thread = new Thread(this);
thread.start();
}
public static void main(String[] args) {
ThreadExample example = new ThreadExample();
for(int n =0; n<1000; n++){
System.out.println("main thread "+i);
i++;
}
}
public void run(){
for(int index=0; index<1000; index++){
System.out.println("Sub thread "+i);
i++;
}
}
}
And when run, the result is:
main thread 0
Sub thread 0
Sub thread 2
Sub thread 3
Sub thread 4
Sub thread 5
Sub thread 6
Sub thread 7
Sub thread 8
Sub thread 9
Sub thread 10
Sub thread 11
Sub thread 12
main thread 1
....
I know thread that run don’t follow by its order. But, the thing that I don’t understand is: why main thread prints 1 (it prints variable i), when variable i has come to 12 ? (because subthread has printed to 12).
Thanks 🙂
Most likely, the explanation is that there’s a large delay between when the text is prepared to be printed and when it can actually be printed. The main thread prepared the statement “main thread 1” and then had to wait until the sub thread released the lock on
System.out, and it acquired the lock, in order to actually print it.If you make
ivolatile, and it still happens, then this is pretty much the only explanation.