【发布时间】:2013-04-01 23:55:02
【问题描述】:
问题如下,因为屏障只使用down()调用,所以它会等待n个线程到达,然后在临界区中一起执行所有n个线程现在如何我是否通知调用 barrier.down 的线程它现在可以继续了。我尝试在 phase2() 之后添加 notifyAll() 但这不起作用。帮助? :)
public class cyclicBarrier {
private int n;
private int count;
private semaphore mutex;
private semaphore turnstile;
private semaphore turnstile2;
public cyclicBarrier(int n){
this.n = n;
this.count = 0;
this.mutex = new semaphore(1);
this.turnstile = new semaphore(0);
this.turnstile2 = new semaphore(0);
}
public synchronized void down() throws InterruptedException{
this.phase1(); //waits for n threads to arrive
this.phase2(); //waits for n threads to execute
}
private synchronized void phase1() throws InterruptedException {
this.mutex.down();
this.count++;
if(this.count == this.n){
for(int i = 0; i < this.n; i++){
this.turnstile.signal(); //when n threads received then move on to phase 2
}
}
this.mutex.signal();
this.turnstile.down(); //keeps waiting till I get n threads
}
private synchronized void phase2() throws InterruptedException {
this.mutex.down();
this.count--;
if(this.count == 0){
for(int i = 0; i < this.n; i++){
this.turnstile2.signal(); //reset the barrier for reuse
}
}
this.mutex.signal();
this.turnstile2.down(); //keeps waiting till n threads get executed
}
}
public class semaphore {
private int counter;
public semaphore(int number){
if (number > 0) {
this.counter = number;
}
}
public synchronized void signal(){
this.counter++;
notifyAll();
}
public synchronized void down() throws InterruptedException{
while (this.counter <= 0){
wait();
}
this.counter--;
}
}
【问题讨论】:
-
我不应该使用内置的 cyclicBarrier :)
-
是的,信号量也是 :)
-
当只有一个线程被释放时,我讨厌使用
notifyAll()。 -
我认为你不能使用
AtomicInteger和朋友? -
我不知道什么是 AtomicInteger... 我应该绑定 2 根氢线和 1 根氧线。即每 2 个氢气线程在屏障处等待,直到氧气线程到达,然后所有线程都被执行。我已经追踪了一切,所以我几乎可以肯定问题出在障碍物上。问题是我看不出问题出在哪里:S
标签: java multithreading semaphore cyclicbarrier