首页 > 解决方案 > 如何在等待()中停止线程

问题描述

 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() ???

标签: javamultithreadingreturnwaitnotify

解决方案


如果您阅读Object::wait文档,它会说以下内容:

导致当前线程等待,直到另一个线程为此对象调用 notify() 方法或 notifyAll() 方法,或某个其他线程中断当前线程,或经过一定的实时时间。

所以你需要中断线程。


推荐阅读