multithreading - java: are global variables visible in threads -
if declare global variable in main thread, suppose main thread run new thread, can new thread access global variable in main thread?
"msg" string variable acces
/* simple banner applet. applet creates thread scrolls message contained in msg right left across applet's window. */ import java.awt.*; import java.applet.*; /* <applet code="simplebanner" width=300 height=50> </applet> */ public class appletskel extends applet implements runnable { string msg = " simple moving banner."; //<<-----------------variable access thread t = null; int state; boolean stopflag; // set colors , initialize thread. public void init() { setbackground(color.cyan); setforeground(color.red); } // start thread public void start() { t = new thread(this); stopflag = false; t.start(); } // entry point thread runs banner. public void run() { char ch; // display banner for( ; ; ) { try { repaint(); thread.sleep(250); ch = msg.charat(0); msg = msg.substring(1, msg.length()); msg += ch; if(stopflag) break; } catch(interruptedexception e) {} } } // pause banner. public void stop() { stopflag = true; t = null; } // display banner. public void paint(graphics g) { g.drawstring(msg, 50, 30); g.drawstring(msg, 80, 40); } }
variables visible several threads tricky. strings, however, immutable, simplifies situation.
it visible, when modified ordinary value available other threads not guaranteed. should make volatile
, not cached thread locally. use local variable build new string before assigning msg
.
if intend modify stopflag
other threads, should volatile
.
Comments
Post a Comment