gpt4 book ai didi

java - 在Java中退出我自己的线程

转载 作者:行者123 更新时间:2023-12-01 14:21:57 25 4
gpt4 key购买 nike

好的,我下面有以下代码

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;

另一种方法是使用中断:

while(!Thread.currentThread.isInterrupted()) {
... logic
if(condition) {
Thread.interrupt();
}
}

关于java - 在Java中退出我自己的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17462817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com