【问题标题】:Java Custom Barrier ImplemenationJava 自定义屏障实现
【发布时间】:2020-07-30 00:09:03
【问题描述】:

首先,这是家庭作业,所以我只是在寻找可能看的地方的提示和指针。

我打算创建多个进程并通过屏障发送它们

Main.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
        }
    }

然后是我的 Barrier.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

我认为我对这应该如何工作的理解很接近,但我错过了一些东西。谢谢大家。

【问题讨论】:

    标签: java multithreading barrier


    【解决方案1】:

    wait 只是等待,notifyAll 唤醒所有等待的线程。所以如果你打电话

    wait();
    notifyAll();
    

    这将永远不会终止,因为线程在等待中等待并且没有线程会每次都到达 notifyAll。有一种使用 wait 的规范形式 notifyAll(参见 Brian Goetz 等人的 Java Concurrency in Practice)。这是这个表格:

    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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-25
      • 2013-04-09
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      相关资源
      最近更新 更多