[英]How to completely stop a thread once it has been interrupted?
在當前代碼中,我正在創建一個實現runnable
的線程。 我從主啟動它,然后讓主打斷它。 但是,一旦被中斷,它將繼續運行。 我希望線程完全停止。
線程類:
public class MyThread implements Runnable {
@Override
public void run() {
// string relating to the threads name
// Note that you actually set the threads name in the main
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " is now started...");
System.out.println(threadName + " about to count down...");
for (int loop = 100; loop > 1; loop--) {
try {
//for 0.5 seconds
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println(threadName + " was Interupted!");
}
System.out.println(loop);
}
}
}
主要:
public class Runner {
public static void main(String[] args) {
//Create thread from class
MyThread myt= new MyThread();
//Passing in the thread from class and also naming it
Thread t= new Thread(myt, "My Thread");
//Actually starts the thread
t.start();
//Main thread has a sleep for 5 seconds then interrupts t
try {
Thread.sleep(5000);
t.interrupt();
System.out.println("Interupting...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
輸出(注意線程如何不停止):
My Thread is now started...
My Thread about to count down...
100
99
98
97
96
95
94
93
92
Interupting...
java.lang.InterruptedException: sleep interrupted
My Thread was Interupted!
91
at java.lang.Thread.sleep(Native Method)
at threads.MyThread.run(MyThread.java:22)
at java.lang.Thread.run(Unknown Source)
90
89
88
87
86
85
只是break
循環:
catch (InterruptedException e) {
e.printStackTrace();
System.out.println(threadName + " was Interupted!");
Thread.currrentThread().interrupt();
break;
}
只需使用一個boolean
標志,該標志將在run()
方法中執行任何操作之前檢查,並根據其狀態執行所需的任何操作。 確保它應該是volatile
。
只需調用myt.setRunning(false)
而不是t.interrupt()
示例CDE:
class MyThread implements Runnable {
private volatile boolean isRunning=true;
@Override
public void run() {
for (int loop = 100; loop > 1; loop--) {
if(!isRunning){
// break or do whatever is needed here
}
}
}
}
只要正確地編寫run()方法,即可使其在中斷時脫離循環,而不僅僅是繼續。
線程確實具有stop()方法,但出於某種原因不建議使用; 它將使事物處於不一致甚至潛在的不穩定狀態。 不要使用它!
對於這樣的重復任務,您還可以使用TimerTask
:
請注意,此代碼不會從零停止。
public class CountdownTask extends TimerTask {
private int from;
public CountdownTask(int from) {
this.from = from;
}
@Override
public void run() {
System.out.println(from--);
}
}
private void example() throws InterruptedException {
Timer timer = new Timer("Countdown");
timer.schedule(new CountdownTask(100), 0, 500);
Thread.sleep(2000); //do something
timer.cancel(); //stop task
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.