multithreading - Java IO's implements on thread variable sharing -
this question has answer here:
i confused code snippet this:
public class learntest { private static boolean tag = true; private static int = 0; public static void main(string[] args) { new thread(new runnable() { @override public void run() { while (tag) { //system.out.println("ok"); i++; } } }).start(); try { thread.sleep(1000); }catch (exception e) { e.printstacktrace(); } tag = false; system.out.println(i); } }
in code, have new-thread
, main-thread
.the result code random value of i
, new-thread
not exit.because new-thread
not new tag
value.
if change define of tag
decorated volatile
, print value of i
, new-thread
exit. because volatile
keep visibility thread.
but when cannel comment commentted code line,and thetag
not decorated witch volatile
,it print "ok" , exit.
why?
what suppose java's io synchronized
, force tag
side value of new-thread
refresh main shared memory.
this's corret?
without volatile
thread not guaranteed see changes value. may see them.
in case adding system.out.println()
results (apparently) in value being removed cache, it's fetched main memory @ point. without println()
value remains in cache, , infinite (or @ least long) loop.
that's 1 difficulty concurrent programming, code may appear work correctly, there's no way always works correctly.
Comments
Post a Comment