我試圖停止一個Java線程,如果它運行6000毫秒。停止或中斷Java線程
以下代碼殺死線程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.");
}
}
}
該代碼看起來不錯,但我還沒有嘗試過。你看到了什麼結果? – markspace
'start()'方法是怎麼回事?你能打印你的日誌並調用'super.start()'嗎?我不認爲需要嵌套的線程。 –