【问题标题】:Can't wake up threads无法唤醒线程
【发布时间】:2015-05-03 10:49:46
【问题描述】:

我在唤醒线程时遇到问题。

在我的程序中必须有一个名为 Bus 的移动线程和几个试图进入 Bus 去其他地方的登山者。

巴士必须始终处于行驶状态(等待登山者进出时除外),登山者必须查看巴士是否在正确的位置,以便他们可以进出。

所以我编写了这段代码,但我无法让它工作,似乎总线无法唤醒线程,但我无法想出另一个解决方案,我不知道出了什么问题。

¿我如何向登山者发出信号让他们醒来并上车?

public class Bus extends Thread
{
boolean pointA=true, pointB=false;

public Bus() {
    start();
}

@Override
public void run()
{
    while(true)
    {
        waiting();
        goA();
        waiting();
        goB();
    }       
}        

public synchronized void waiting() {
    try {
        Thread.sleep((int)(1000));   //waiting for the climbers
    } catch (InterruptedException ex) {}
}

public synchronized void goB() {
    pointA = false;
    try {
        Thread.sleep((int)(1000));   //travelling
    } catch (InterruptedException ex) {}
    pointB = true;
    notifyAll();  //is in B, the climbers can get out
}

public synchronized void goA() {
    pointB = false;
    try {
        Thread.sleep((int)(1000));
    } catch (InterruptedException ex) {}
    pointA = true;
    notifyAll();  //is in A, the climbers can get in
} 

public synchronized void enter(Climber c, ArrayThreads fA, ArrayThreads fBus){

        while(!pointA){   //wait until Bus reaches pointA
            try{wait();}catch(InterruptedException e){}
        } 
        fA.out(c);     //Leaves station
        fBus.put(c);   //Enters the bus

        while(!pointB){    //wait until Bus reaches pointB
        try{wait();}catch(InterruptedException e){}
        }

        fBus.out(c);   //Leaves Bus

}

}

【问题讨论】:

  • 你的类有编译错误:public synchronized void wait()“不能从对象覆盖最终方法”。请在询问之前提交工作代码。
  • 哪一个?我没有添加进口,也没有添加主类或登山者类,也许就是这样。该代码对我有用,但问题是登山者一直在等待。
  • 即使您添加了正确的导入和Climber 类,您仍然无法重新定义wait() 方法,因为它在Object 中声明为final。你用的是哪个版本的JDK?
  • 你是对的,对不起,我在输入和复制粘贴时错误地更改了方法的名称,它不是称为 wait(),现在它应该像我说的那样工作。跨度>
  • 好的,现在好多了。什么是 ArrayThreads 类型? JDK中没有这种类型。

标签: java multithreading wait notify


【解决方案1】:

您提供的代码包含重写的等待方法。但是在 Object 类中等待方法是最终的。所以不能覆盖它。

您的代码中没有问题,您是从同一个线程调用 wait 和 notifyall 方法。

在您给出的代码中,您调用同步方法 wait() 并期望其他同步方法 goA() 会通知,但该方法永远不会被调用。由于等待方法正在持有锁。

所以,修改你的程序,让它有两个线程,一个用于总线,一个用于创建登山者可能会有所帮助

【讨论】:

  • 对不起,我写代码的时候打错了,现在修复了,总线线程从不等待,只调用一个方法让它进入睡眠状态,唯一等待的应该是线程中的爬虫方法 Enter,并被 Bus Thread 唤醒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多