好的,我在下面的代码
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!!
}
}
}
}
});
}
上面的代码在我更大的代码中,但是我想知道的是如何通过在线程内部运行代码来停止线程运行。我该如何阻止它?
最佳答案
停止线程的两种方法,一种已经通过条件逻辑和break
/ return
使用:
DayProcessor.isDayProcessorActive = false;
break;//return;
其他方法是使用
interrupt
:while(!Thread.currentThread.isInterrupted()) {
... logic
if(condition) {
Thread.interrupt();
}
}