Wednesday, February 10, 2010

Guarded Blocks in Java

In Java Threads, there are many times when it's necessary to wait until another process finishes. In this post, an example is below:

/*
* @author Miguel Angel Vega Pabon
* @version 1.0, Developed with Netbeans 6.8
*/
public class GuardedBlocks {

int times = 0;

/** Default constructor */
public GuardedBlocks() {
}

public synchronized void readData() {
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(20);
times++;
System.out.println(times + "%");
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
notifyAll();
}

public synchronized void verify() {
if (times != 100) {
try {
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
System.out.println("Data has been aquired successfully");
}

public static void main(String args[]) {
final GuardedBlocks gb = new GuardedBlocks();
Thread t = new Thread() {
public void run() {
gb.verify();
}
};
gb.readData();
t.start();
}
}


As you can see, the method readData is called first, and then the thread starts.
The method verify waits until the method readData finishes.
:)