Java Реализация пользовательских барьеров - PullRequest
1 голос
/ 16 апреля 2020

Во-первых, это домашняя работа, поэтому я ищу только подсказки и указатели того, где, возможно, искать.

Я намерен создать несколько процессов и отправить их через барьер

Главное. java

for (int x=0; x!=threadCount+1; x++){
            Process newThread = new Process(barrier, x, sleepTime);
            newThread.run();
        }

Процесс. java

public void run() {
        try {

            Thread.sleep(100 + sleepTime);
            barrier.joinBarrier(this);

        } catch (InterruptedException e) {
            // do nothing
        }
    }

, а затем и мой барьер. java

public synchronized void barrier() throws InterruptedException{
        wait();
    }

    public synchronized void releaseBarrier(){
        notifyAll();
    }

    public void joinBarrier(Process p) throws InterruptedException {
        System.out.println(p.getName() + " waiting on barrier");

        if(blocking){
            threadsWaiting++;
            barrier();
            releaseBarrier();
        }
        else{
            System.out.println(p.getName() + " passed the barrier");
        }
    }

Возможно, мое понимание неверно но я ожидал, что первый поток будет ждать, затем второй поток будет ждать, однако мой вывод просто останавливается, поток всегда ожидает

Number of threads = 20
Barrier size = 10
Thread 0 waiting on barrier

Process finished with exit code -1

Я думаю, мое понимание того, как это должно работать, близко, но я что-то упустил Спасибо всем.

1 Ответ

0 голосов
/ 17 апреля 2020

wait просто ждет и уведомляет. Все будит весь ожидающий поток. Поэтому, если вы вызовете

wait();
notifyAll();

, это никогда не прекратится, так как поток ожидает в ожидании, и ни один поток не будет достигать notifyAll. Существует каноническая форма для использования wait, notifyAll (см. Java Concurrency in Practice, Brian Goetz et al). Вот эта форма:

synchronized{    // always execute the complete block in a synchronized block to avoid race conditions
    execute the action // as first update the count or whateverto mae sure that this will be done everytime
    notifyAll  // then inform all other threads about the change
    while( ! conditionTrue ) // now check the condition in a loop
    {
       wait(); // wait till the condition becomes true
    }
}
...