java - 我怎么知道是谁造成了中断异常?(爪哇)
问题描述
我在我的代码中使用中断()从一个线程向另一个线程发出信号,以从“无休止”(最大时间)睡眠中唤醒并在一段时间内验证一个条件。我也在使用监视器(同步块、通知和等待)和同步方法。我写我的代码的方式是一些线程休眠直到它们得到一个中断,但是一些中断在它们不应该被唤醒时唤醒线程(它们必须模拟它们正在做其他事情睡觉)。问题是我无法找到不应该执行中断()的线程,我怎么能找到它?
以这种方式使用中断()进行编码是一种好方法吗?
那是睡眠被打断但不应该被打断的代码
private void medicalVisit(int number) {
long sleepTime = (long) ((Math.random() * 2 + 0.5) * 1000); // 500 <= sleepTime (in msec) <= 2500
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.out.println(this.getName()+" ERROR, interrupt from sleep, id: 2 (medicalVisit)");
e.printStackTrace();
}
System.out.println(this.getName()+" - "+number+"° medical visit ended");
}
这是启动中断的代码示例
private void handlerYellowPatient() {
Iterator<Patient> patientIt = yellows.iterator();
while(patientIt.hasNext()) {
Patient p = patientIt.next();
p.itsTurn = true;
p.interrupt();
yellows.remove(p);
}
}
这是一个正确“消耗”中断的代码示例
private void waitUntilItsTurn(int number) {
// simulating the period of time before entering in guard
long sleepTime = (long) ((Math.random() * 2 + 0.5) * 1000); // 500 <= sleepTime (in msec) <= 2500
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// must not be awaken while here
System.out.println(this.getName()+" ERROR MAYBE, interrupt from sleep, id: 1");
e.printStackTrace();
}
WMan.addPatient(this, WMan);
while (!itsTurn) {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
// WMan handlerRedPatient interrupt#1
System.out.println(this.getName()+" - the wait is over, it's my turn for the "+number+"° times");
}
}
itsTurn = false;
}
希望这些代码可以提供帮助
解决方案
推荐阅读
- python - 从 Python 中不断更新的文件中读取整个文件数据
- python - 基于多个值条件打印字典键
- gnome - gnome-terminal:“--name”参数仅适用于第一个窗口
- mysql - 插入触发器之前的MYSQL:无法更新存储函数/触发器中的表,因为它已经在使用中
- ajax - 如何在 Laravel 中使用 Ajax?
- django - 如何为Django中尚不存在的表设置外键属性的默认值?
- android - 没有应用程序正在启动或运行
- c - 还有其他类型的控制台事件吗?
- javascript - Metalsmith 布局导致“没有要处理的文件”错误
- php - 如何记录每个用户尝试登录的每个 IP 地址?