Associate
- Joined
- 23 Aug 2004
- Posts
- 1,493
I have a barrier class in java. The idea is threads are held at a barrier until the release method is called at which point they can pass the barrier. When I try and call the release method, nothing happens. I've tried using system.out.println to test whether the method is ever reached and it doesn't output. I believe that the thread is stuck in the checkIN method. Here's my code, can anyone see the flaw that would prevent me using the release method?
Many thanks!
Many thanks!
Code:
public class Worker extends Thread {
public static final int N = 50; //say
private static double[] a = new double[N];
private static double[] b = new double[N];
private static double[] c = new double[N];
private static SignallingBarrier b1 = new SignallingBarrier(N);
private int index;
public Worker(int index) {
this.index = index;
}
public synchronized void run() {
b1.checkIn();
b1.release();
}
// other methods of worker
// e.g. static accessor methods for the arrays a, b and c
}
Code:
public class SignallingBarrier {
private int threadWaiting;
private boolean releasing;
private int numThreads;
public SignallingBarrier(int N) {
numThreads = N;
threadWaiting = 0;
releasing = false;
}
public synchronized void checkIn() {
//prevent extra threads arriving during the release
// from sneaking through
while(releasing) {
try {
wait();
} catch(InterruptedException e ) {};
}
System.out.println("There are : " + threadWaiting + " threads waiting");
threadWaiting++;
//wait for release to arrive.
while (!releasing) {
try {
wait();
} catch(InterruptedException e) {};
}
threadWaiting--;
}
public synchronized void release() {
System.out.println("There are : " + threadWaiting + " threads waiting abc");
if (threadWaiting > 0){
releasing = true;
notifyAll();
while (threadWaiting > 0){
try {
wait();
}catch (InterruptedException e) {};
}
if(threadWaiting == 0){
releasing = false;
notifyAll();
}
}
}
}
Code:
public class TestBarrier{
public static void main(String args[])
throws InterruptedException {
final int N = Worker.N;
Worker[] a = new Worker[N];
// create threads and add to the array
for(int i = 0; i < N; i++)
{
a[i]= new Worker(i);
}
// start the N threads
for(int i = 0; i < N; i++)
{
a[i].start();
}
//wait for all the slaves to terminate
for(int i = 0; i < N; i++)
{
a[i].join();
}
}
}