I came across another proposal to terminate the thread. May I know this is the right way? Or does it depend?
Using Thread Variable http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html
private volatile Thread blinker; public void stop() { blinker = null; } public void run() { Thread thisThread = Thread.currentThread(); while (blinker == thisThread) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); } }
Using a boolean flag
private volatile boolean flag; public void stop() { flag = false; } public void run() { while (flag) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); } }
Using Thread Variable with Interrupt
private volatile Thread blinker; public void stop() { blinker.interrupt(); blinker = null; } public void run() { Thread thisThread = Thread.currentThread(); while (!thisThread.isInterrupted() && blinker == thisThread) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } repaint(); } }
source share