This is because the application doesn't wait for the thread to be over to continue its execution. It seems like most of the time the affectation
a = 1
is faster than the thread to be executed. That's why It is important in some cases to wait for your thread to be over.
If you set up a breakpoint to your a = 1 line, you will see 0 is printed.
Now try this :
public class TestThread {
static int a = 0;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread() {
@Override
public void run() {
System.out.println(a);
}
};
thread.start();
thread.join();
a = 1;
}
}
Using the join()
method, It will wait for thread to be finished.
You can also use the static Thread.sleep function but it is definitely not how I recommend to solve this issue since you can't know for sure how long it takes before your thread is complete.
thread.start();
Thread.sleep(100);
a = 1;