好的,我在下面有以下代码
public static void StartDayProcessor(){
new Thread(new Runnable() {
public void run() {
long lastSec = 0;
while(DayProcessor.isDayProcessorActive){
long sec = System.currentTimeMillis() / 1000;
if (sec != lastSec) {
DayProcessor.secondsActive++;
DayProcessor.timeLeftInSecs = DayProcessor.day.getTimeLimitInSecs() - DayProcessor.secondsActive;
System.out.println("Seconds left for this day: " + DayProcessor.timeLeftInSecs);
if(DayProcessor.timeLeftInSecs == 0){
DayProcessor.isDayProcessorActive = false;
break;
//exit my own thread here!!
}
}
}
}
});
}
上面的代码在我更大的代码中,但我想知道的是如何通过在线程内部运行代码来停止运行的线程。我怎么能阻止它?
答案 0 :(得分:1)
两种停止线程的方法,一种已经通过条件逻辑和break
/ return
使用的线程:
DayProcessor.isDayProcessorActive = false;
break;//return;
其他方式是使用interrupt
:
while(!Thread.currentThread.isInterrupted()) {
... logic
if(condition) {
Thread.interrupt();
}
}
答案 1 :(得分:0)
你可以使用return。
如果你想在特定的条件下返回你的线程,你可以有一个全局变量amd当你想要返回你的线程时将它设置为true,并在你的线程中检查变量的值并只调用return。 / p>
它可以帮助您甚至从主线程控制线程,您可以将变量值设置为true。
答案 2 :(得分:0)
public static void StartDayProcessor(){
new Thread(new Runnable() {
public void run() {
long lastSec = 0;
LabeledLoop:
while(DayProcessor.isDayProcessorActive){
long sec = System.currentTimeMillis() / 1000;
if (sec != lastSec) {
DayProcessor.secondsActive++;
DayProcessor.timeLeftInSecs = DayProcessor.day.getTimeLimitInSecs() - DayProcessor.secondsActive;
System.out.println("Seconds left for this day: " + DayProcessor.timeLeftInSecs);
if(DayProcessor.timeLeftInSecs == 0){
DayProcessor.isDayProcessorActive = false;
break LabeledLoop;
//exit my own thread here!!
}
}
}
}
});
}
通过打破循环,线程应该自行停止。
答案 3 :(得分:0)
停止线程的常用方法,包括
我不建议中断线程,因为这意味着线程没有正常终止,资源可能仍未清除。