At times we often need to fetch an object which might take a long time. Our preferred way of doing that, especially when we are on a UI thread, is to spawn a different thread so as to keep the UI responsive (this is just one of the many use cases that I can think of now). But since we need that object to proceed further in the current execution, we have to resort to some sort of wait/notify mechanism. The following code demoes a very simplistic approach using the regular wait()/notify().
package com.swayam.thread.test;
/**
*
* @author paawak
*
*/
public class WaitNotifyExample {
private Object lock = new Object();
public WaitNotifyExample() {
}
public void runLongTask() {
Thread job = new Thread(new Runnable() {
public void run() {
System.out.println("Long task started");
try {
int maxCount = 1000;
// int maxCount = Integer.MAX_VALUE;
// do some long task
for (int i = 0; i < maxCount; i++) {
System.out.println(i);
}
System.out.println("Long task done.");
} finally {
System.out.println("About to notify lock...");
synchronized (lock) {
lock.notifyAll();
}
System.out.println("Lock notified");
}
}
});
// job.setPriority(Thread.MAX_PRIORITY - 2);
System.out.println("Starting a long task...");
job.start();
System.out
.println("Pausing normal execution and waiting for long task to finish...");
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Resuming normal execution as long task is done.");
}
public static void main(String[] a) {
new WaitNotifyExample().runLongTask();
}
}
Note: This is far from fool proof. One case where it will fail is if the long task is over before that lock.wait() is called.