A different way to stop a thread is the right way

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(); } } 
+4
source share
3 answers

None of them are the "right" way, they are all valid. Which one you use depends on your circumstances, and which one is best for you.

Until you use Thread.stop() , and you remove all resources left open by your threads (connections, temporary files, etc.), then it doesn’t matter how you do it.

+6
source

I always use a boolean flag - its the easiest. Its very short and understandable for reviewers, but it has a handycap that you cannot interrupt the sleep call. You should only use interrupt options to stop the flow in time. And as the scaffman said - Do not use Thread.stop() !

+2
source


what about this

 class Tester { public static void main() { Try t = new Try(); Thread.sleep(10); //wait for 10 milliseconds t.interrupt(); // 'interrupt' ie stop the thread } } public class Try extends Thread { @override public void interrupt() { //perform all cleanup code here this.stop(); /*stop() is unsafe .but if we peform all cleanup code above it should be okay ???. since thread is calling stop itself?? */ } } 
0
source

Source: https://habr.com/ru/post/1335726/


All Articles