java - Calling and using the .interrupt() method? -
how call .interrupt()
method? when have thread.sleep(1000)
, when , call .interrupt()
method? after? want stop thread.sleep(1000)
midway.
edit::
i'm having trouble stopping thread in middle. part of code, in stoplightthread
class have problems on first if statement. supposed wait @ least 10 secs allow user press button can change light, if button pressed should stop running thread in case thread.sleep(40000)
. happens when press button changes light not stop thread. if press button while there still 20secs left add 20secs 10secs yellow light, making yellow 30 secs.
edit: if wondering, stoplightcanvas.x == 3
green, stoplightcanvas.x == 2
yellow, , stoplightcanvas.x == 1
red.
class stoplightcanvas extends canvas implements actionlistener { public void actionperformed(actionevent e) { if (e.getsource() == cross) { ispressed = true; if (x == 3 && cancross) x = 2; } repaint(); } } class stoplightthread extends thread { stoplightcanvas stoplightcanvas; stoplightthread(stoplightcanvas stoplightcanvas) { this.stoplightcanvas = stoplightcanvas; } public void run() { if (stoplightcanvas.x == 3){ thread.sleep(10000); stoplightcanvas.cancross = true; thread.sleep(40000); if(stoplightcanvas.ispressed) stoplightthread.interrupt(); } else if (stoplightcanvas.x == 2) { thread.sleep(10000); } else if (stoplightcanvas.x == 1) { thread.sleep(60000); } } catch (interruptedexception e){} stoplightcanvas.togglecolor(); stoplightcanvas.repaint(); } } }
if going call interrupt()
@ all, you'd call different thread sleep().
if want interrupt sleep() midway same thread, can this:
thread.sleep( 500 ); ... thread.sleep( 500 );
all said, sleep() can code smell.
edit (after op edit):
call interrupt() on stoplightthread gui thread in actionperformed() method.
Comments
Post a Comment