java - Multithreading: Switching context -
i have written small sample code:
public class button2 implements runnable{ jbutton jbutton = new jbutton(); static boolean changecontext = false; public button2(){ jbutton.settext("buttontwo"); jbutton.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { changecontext = true; ((jbutton)e.getsource()).setenabled(false); } }); } @override public void run() { system.out.println("buttontwo run..."); jbutton.setenabled(true); while(true){ if(changecontext) break; } changecontext = false; } }
when run like:
button2 threadtwo = new button2(); thread thread2; try{ thread2 = new thread(threadtwo); thread2.start(); thread2.join(); }catch(exception ex){ system.out.println("Ëxception caught"); }
it never comes out, after clicking button.
if add sysout
or thread.sleep(1)
after while(true) in run method
, comes out of while loop. can possible reason?
i assume you're running bottom portion on edt. you're creating button (and add ui somehow) start thread , make edt wait thread die (thread2.join()
), hence edt can't process events , changecontext = true
never called.
that adding makes loop end due missing braces:
this ends loop if changecontext
true:
if(changecontext) break;
i assume did this:
if(changecontext) thread.sleep(1); break;
the above calls sleep if changecontext
true , ends loop (the break
not inside if-block anymore. if want consistent behavior write this:
if(changecontext) { thread.sleep(1); break; }
btw, apple had security issue last year had similar source (a double break
, no braces).
Comments
Post a Comment