我想在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);
}
}
}
我不确定我是否找到了实现此功能的方法。任何帮助将不胜感激!
答案 0 :(得分:1)
我有一些输入,
在课程计时器中,您需要有一个工作人员类的实例,以便您可以调用parent.interrupt()。
为此,我建议您为 Timer 类创建一个新的构造函数,如下所示
public class Timer implements Runnable {
Worker parent;
public Timer(Worker parent)
{
this.parent = parent;
}
@Override
public void run(){
try {
Thread.sleep(3000);
//Interrupt the parent thread it was called from..
//In this case, an instance of Worker.
parent.interrupt();
} catch (InterruptedException e) {
System.exit(1);
}
}
}
其次,在 Parent 类中,您需要将序列更改为以下内容,
timer.start()
Thread.sleep(7000);
否则,工作线程将在启动定时器线程之前休眠。
我希望它有所帮助..