Ich habe zwei Klassen erstellt, CheckTimer
wird verwendet, um zu unterbrechen, wenn 0,3 Sekunden vergangen sind. Ich bemerkte, dass thread.interrupted()
in CheckTimer.run()
ausgeführt wurde, aber InterruptedException
in der Hauptfunktion wurde nicht geworfen, weiter ohne einen Anhaltspunkt zu stoppen, warum? Ist nicht thread1.interrupted()
soll aufhören thread1
?InterruptedException wurde nicht ausgelöst, wenn der Thread unterbrochen wurde
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();
}
}
}
Es gibt keinen Aufruf 'thread1.interrupt()' überall in Ihrem Beispiel. –