Blocking and unblocking thread with Java concurrency API_176816136 - Gumtree/gumtree GitHub Wiki
Created by Tony Lam, last modified on Sep 01, 2010
public static void main(String[] args) {
// Lock
final ReentrantLock lock = new ReentrantLock();
//
final Condition countCompleted = lock.newCondition();
//Thread to wake up the condition
Thread thread = new Thread(new Runnable() {
public void run() {
int i = 0;
while (i < 5) {
System.out.println("Counting " + i + "...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
i++;
}
// Locking is require before condition gets called
lock.lock();
// Wake up after 5 sec
countCompleted.signal();
lock.unlock();
}
});
thread.start();
// Locking is require before condition goes into sleep
lock.lock();
try {
System.out.println("Start to wait...");
// Sleep until condition is called
countCompleted.await();
System.out.println("Finished waiting.");
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
}
Document generated by Confluence on Apr 01, 2015 00:11