简体   繁体   中英

Can't wake up threads

I've got problems waking up Threads.

In my program there must be a moving Thread called Bus and several climbers who tries to enter the Bus to go somewhere else.

The Bus must be always in movement(except when is waiting for the climbers to get in/out) and the climbers must see if the Bus is in the correct place so they can get in/out.

So i made this code, but i can't get it to work, it seems like the Bus can't wake up the Threads but i can't came up with another solution and i don't know what's wrong.

¿How can i signal the climbers to wake up and get into the 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

}

}

The code that you have provided contains overrided wait method. But in Object class wait method is final. So one cannot override it.

No the problem in your code is that, you are calling wait and notifyall method from the same thread.

In you given code, you call synchronized method wait() and expect that other synchronized method goA() will notify, but that method will never be called. As wait method is holding lock.

So, modifying you program which have two thread, one for bus and one for creating climbers might help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM