gpt4 book ai didi

java - 停止或中断 Java 线程

转载 作者:行者123 更新时间:2023-12-01 16:51:15 25 4
gpt4 key购买 nike

如果 java 线程运行了 6000 毫秒,我会尝试停止该线程。

下面杀死线程 R1 的代码未能停止该线程。您能更正代码吗?

我已经尝试使用 while (!Thread.currentThread().isInterrupted()) 来停止线程。

import java.time.Duration;
import java.time.Instant;

class ThreadDemo extends Thread {
private Thread t;
private String threadName;

ThreadDemo(String name) {
threadName = name;
System.out.println("Creating " + threadName);
}

@Override
public void run() {
System.out.println("Running " + threadName);
try {
while (!Thread.currentThread().isInterrupted()) {
for (int i = 100; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(600);
}
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
Thread.currentThread().interrupt();

}
System.out.println("Thread " + threadName + " exiting.");
}

@Override
public void start() {
System.out.println("Starting " + threadName);
if (t == null) {
t = new Thread(this, threadName);
t.start();
}
}
}

public class Killthread {

public static void main(String args[]) throws InterruptedException {
Instant timeBefore = Instant.now();

ThreadDemo R1 = new ThreadDemo("Thread-1");
R1.start();
System.out.println("Afte thread start");
Thread.sleep(6001);
Instant timeAfter = Instant.now();
if (Duration.between(timeBefore, timeAfter).toMillis() > 6000) {
R1.interrupt();
// R1.stop();
System.out.println("Thread Interrupted due to Time limitation.");

}
}
}

最佳答案

您的代码中存在两个问题,首先您的主线程 hibernate 时间不够长,其次您中断了错误的线程。

6001 毫秒不足以保证您的持续时间检查正确。当我运行你的代码时,主要方法很少进入 if block 。如果您将其更改为 sleep 6100 毫秒,它应该始终调用中断。

你的第二个问题是你正在中断R1,但你需要中断t

如果您在 ThreadDemo 中重写 interrupt() 以将调用传递给 t,那么它将接收中断并中断其执行线程。

例如

@Override public void interrupt() {
t.interrupt();
}

关于java - 停止或中断 Java 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39707220/

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