【发布时间】: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