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