0
我想在一個Worker線程內定義一個Timer線程,如果Worker線程睡眠時間過長,這將調用Worker線程的中斷方法(該休眠時間是動態定義的)。因此,在本質的代碼將如下所示:使用從線程喚醒睡眠主線程
public class Worker implements Runnable {
private Timer timer;
@Override
public void run(){
try {
Thread.sleep(7000);
timer.start()
//timer must call this Thread's
//interrupt method if it sleeps
//for more than a specified time.
} catch (InterruptedException e) {
System.out.println("I was awakened. Gotta work!")
}
}
}
而且這可能是Timer類實現的:
public class Timer implements Runnable {
@Override
public void run(){
try {
Thread.sleep(3000);
//Interrupt the parent thread it was called from..
//In this case, an instance of Worker.
} catch (InterruptedException e) {
System.exit(1);
}
}
}
我不知道我已經找到一種方法來實現這一功能。任何幫助將非常感激!
我已經試過了......,但parent.interrupt()顯示爲syntatically正確。另外,我在Worker類中添加了一個調用「thread.interrupt()」的interrupt()方法,但都無濟於事。無論如何,我找到了解決辦法。感謝您嘗試不管。 –