java - Thread variable after call start and run -
i realized code:
public class testthread3 extends thread { private int i; public void run() { i++; } public static void main(string[] args) { testthread3 = new testthread3(); a.run(); system.out.println(a.i); a.start(); system.out.println(a.i); } } results in 1 1 printed ... , don't it. haven´t found information how explain this. thanks.
results in 1 1 printed
so first a.run(); called main-thread directly calling a.run() method. increments a.i 1. call a.start(); called forks new thread. however, takes time i++; operation has not started before system.out.println(...) call made a.i still 1. if i++ has completed in a thread before println run, there nothing causes a.i field synchronized between a thread , main-thread.
if want wait spawned thread finish need a.join(); call before call println. join() method ensures memory updates done in a thread visible thread calling join. i++ update seen main-thread. use atomicinteger instead of int wraps volatile int , provides memory synchronization. however, without join() there still race condition between a thread doing increment , println.
// provides memory synchronization internal volatile int private atomicinteger i; ... public void run() { i.incrementandget(); } ... a.start(); // still race condition here need join wait finish a.join(); system.out.println(a.i.get());
Comments
Post a Comment