【发布时间】:2013-03-21 11:02:03
【问题描述】:
public class cyclicBarrier {
private static int n;
private static int count;
private static semaphore mutex;
private static semaphore turnstile;
private static 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();
this.phase2();
}
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();
}
}
this.mutex.signal();
this.turnstile.down();
}
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();
}
}
this.mutex.signal();
this.turnstile2.down();
}
}
&& 这里是类信号量以防万一
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--;
}
}
这是我编写的使用线程实现Cyclicbarriers的代码。 我从书中获取了伪代码以及关于死锁的注释,所以我认为它非常好“虽然可能存在错误”。第一阶段是“到达线程”,第二阶段是“在关键区域一起运行线程”。我的问题如下......如何更改代码以考虑特定类型的线程?例如,有氢线程和氧线程,我希望它们每次在屏障处有 2 个氢原子和 1 个氧原子时执行 bond() 。先感谢您。
【问题讨论】:
标签: java multithreading semaphore cyclicbarrier