java - 如何在等待()中停止线程
问题描述
while (!closingTime){
depot.enterramp();
}
这是启动功能如下
synchronized (list) {
while (list.size() == 0) {
System.out.println(":: DEPOT\t:: " + "NO BUS FOUND IN THE APPROACHES DEPOT, WAITING THE BUS COMING");
try {
list.wait();
} catch (InterruptedException iex) {
iex.printStackTrace();
}
}
目前我的线程正在等待 notify() [此代码在 enterramp() 中]
public class Clock extends Thread {
public void run() {
try {
Thread.sleep(15000);
notifyTime();
} catch (Exception e) {
}
}
public synchronized void notifyTime() {
System.out.println(":: CLOCK\t:: ALERT ALERT !!! DEPOT HAVE TO CLOSE IN 30 MINUTES, NO MORE ACCEPTING THE BUSES");
closingTime = true;
return;
}
这是时钟休眠 15 秒并使关闭时间为真
synchronized (list) {
list.add(bus);
list.notify();
}
这是我通知它的一部分
我面临的问题是当关闭 == true 时,但线程卡在 wait() 区域,当我的关闭时间 == true 时,如何让线程退出 wait() ???
解决方案
如果您阅读Object::wait
文档,它会说以下内容:
导致当前线程等待,直到另一个线程为此对象调用 notify() 方法或 notifyAll() 方法,或某个其他线程中断当前线程,或经过一定的实时时间。
所以你需要中断线程。
推荐阅读
- python - Python:如何在 tkinter 的检查按钮中动态分配变量
- shell - 如何通过 impala shell 脚本显示任何消息
- algorithm - 如何从不接近的 U(a,b) 中抽取 n 个样本?
- python - 公网IP无法访问服务器机器上的scrapyd接口
- react-native - 上下文 API React Native
- javascript - 为什么 id 和 itemId 在该反应代码中从不匹配?
- r - 如何获得我的 VAR 模型的 HAC 标准误差?
- exception - 仅针对特定代码片段覆盖 Eslint 规则
- html - SVG 图标无法正确显示
- php - CodeIgniter,用另一个表中的数据填充数据库表,数组到字符串转换错误