-1
2つのクラスを作成しました.CheckTimer
は、0.3秒が経過したときに割り込みするために使用されます。thread1
私はthread.interrupted()
がCheckTimer.run()
で実行されたが、メイン関数のInterruptedException
は投げられなかったことに気付きました。thread1
は何のヒントもなく実行を続けました、なぜですか? をthread1.interrupted()
は止めますか?スレッドが中断されたときに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 'への呼び出し)'どこでもあなたの例ではありません。 –