-1
我創建了兩個類,CheckTimer
用於在傳遞0.3秒時中斷thread1
。我注意到thread.interrupted()
被執行CheckTimer.run()
,但InterruptedException
在主函數中沒有被拋出,thread1
繼續運行沒有任何停止提示,爲什麼?是不是thread1.interrupted()
應該停止thread1
?當線程被中斷時不會拋出InterruptedException
class CheckTimer extends Thread
{
/** indicate whether the thread should be running */
private volatile boolean running = true;
/** Thread that may be interrupted */
private Thread thread;
private int duration;
private int length;
public CheckTimer(int length, Thread thread)
{
this.duration = 0;
this.thread = thread;
this.length = length;
}
/** Performs timer specific code */
public void run()
{
// Keep looping
while(running)
{
// Put the timer to sleep
try
{
Thread.sleep(100);
}
catch (InterruptedException ioe)
{
break;
}
// Use 'synchronized' to prevent conflicts
synchronized (this)
{
// Increment time remaining
duration += 100;
// Check to see if the time has been exceeded
if (duration > length)
{
// Trigger a timeout
thread.interrupt();
running = false;
}
}
}
}
}
class Thread1 extends Thread {
public void run() {
while(true) {
System.out.println("thread1 is running...");
}
}
}
public class Test {
public static void main(String[] args) {
Thread thread1 = new Thread1();
CheckTimer timer = new CheckTimer(300, thread1);
timer.start();
thread1.start();
try {
thread1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
有()'在你的榜樣任何地方'thread1.interrupt沒有呼叫。 –