| Examples
|
How to be notified once a thread finish? (JDK 1.5) My forum http://forum.java.sun.com/thread.jspa?threadID=5211762 public class TestThread implements Runnable { private BlockingQueue<String> q; public TestThread(BlockingQueue<String> q) { this.q = q; } public void run() { try { System.out.println("Bye, bye forum..."); q.put("done"); } catch(Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws Exception { BlockingQueue<String> q = new LinkedBlockingQueue<String>(); TestThread r = new TestThread(q); Thread t = new Thread(r); t.start(); Thread.sleep(1000); #Wait undefinitely String s = q.take(); #Wait only 2 seconds max #String s = q.poll(2000, TimeUnit.MILLISECONDS); System.out.println("The thread " + s + " has finished"); } } |
How to be notified once a thread finish? (Any JDK)
This my BlockingQueue version working with any JDK
public class MyBlockingQueue {
private boolean done =false;
private Object lock = new Object();
public void threadIsDone() {
done = true;
synchronized(lock) {
lock.notify();
}
}
public boolean waitForThreadDone(long timeout) throws InterruptedException {
synchronized(lock) {
lock.wait(timeout);
}
return done;
}
public void waitForThreadDone() throws InterruptedException {
while(!done) {
synchronized(lock) {
lock.wait();
}
}
}
public static void main(String[] args) throws Exception {
args.getClass();
MyBlockingQueue lock = new MyBlockingQueue();
class MyThread extends Thread {
MyBlockingQueue lock;
public MyThread(MyBlockingQueue lock) {
this.lock = lock;
}
public void run() {
System.out.println("Thread done");
lock.threadIsDone();
}
};
MyThread t = new MyThread(lock);
t.start();
Thread.sleep(2000);
lock.waitForThreadDone();
}
} |
Basic thread synchronization (lock - notify)
Thread main
while(true) {
synchronized(lock) {lock.wait(30000);}
...
}
Thread n
synchronized(lock) {
lock.notify();
} |