![](/img/trans.png)
[英]How do you stop the camera when application is stopped in java openCV?
[英]How do you stop a thread in a Java command prompt that is stopped when the user commands it to stop?
基本上,我有一個在控制台中運行的Java線程,它將無限循環運行,除非用戶輸入“ halt”,否則程序應停止線程並停止控制台。
這是線程的set_interval部分的樣子(用戶可以輸入他們希望在線程之間間隔多長時間的輸入):
public void set_interval(int mins, int secs) {
time = (mins * 60000) + (1000 * secs);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
count += counter;
String name = getName();
Date date = new Date();
System.out.print("\n" + "Thread:" + name + " " + date + " - counter: " + count);
Thread.sleep(time);
} catch(InterruptedException e){
System.out.print(e);
}
}, 0, time);
}
這是主要的樣子: }else if (checkLine.equals("halt")){ Thread test = new Thread("name"); test.interrupt(); break; }
}else if (checkLine.equals("halt")){ Thread test = new Thread("name"); test.interrupt(); break; }
我所看到的每個地方都說要使用中斷,但是此中斷似乎不起作用。 任何人有任何想法嗎? 還是我只是忽略了一些小細節? 我有可能需要使用套接字來解決此問題。
中斷只會中斷您要中斷的線程。 在代碼中,您創建了要中斷的線程,但是不會影響其他線程。
您可以在計時器中中斷線程,除非您記錄了中斷,但繼續進行就好像沒有發生那樣,即不會停止線程。
我將為此使用ScheduleExecutorService,因為它支持shutdownNow()
,它可以停止線程池並中斷所有正在運行的任務。
看一看ScheduledExecutorService ,它可以用來管理您的任務。 使用執行程序服務使Java中的多線程生存更加容易:)
為什么不將計時器移出函數並移入類范圍? 然后調用timer.purge()
或timer.cancel()
嗎? -堅持! 他們僅停止/取消所有非活動任務。 當前執行的任務將永遠不會停止。
您正在嘗試停止當前正在執行的任務。 一種更簡單的方法是:擁有一個AtomicBoolean dontKeepRunning
變量,當您希望任務必須終止時將其設置為true。
像這樣:
private AtomicBoolean dontKeepRunning;
public YourTimerTask(){ dontKeepRunning = new AtomicBoolean();}
public void halt()
{
dontKeepRunning.set(true);
}
public void set_interval(int mins, int secs) {
time = (mins * 60000) + (1000 * secs);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
try {
count += counter;
String name = getName();
Date date = new Date();
System.out.print("\n" + "Thread:" + name + " " + date + " - counter: " + count);
while(dontKeepRunning.get() == false){}
return;
} catch(InterruptedException e){
System.out.print(e);
}
}, 0, time);
}
在所有Thread.interrupt
上發出Thread.interrupt
。 並且這些線程必須支持中斷 。 基本上,線程必須:
Thread.currentThread.isInterrupted()
InterruptedException
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.