- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- import java.util.logging.ConsoleHandler;
- import java.util.logging.Handler;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class ReentrantLockTest implements Runnable {
- private final static Logger logger = Logger.getLogger(ReentrantLockTest.class.getName());
- private ReentrantLock lock = new ReentrantLock();
- private Condition cond = lock.newCondition();
- public ReentrantLock getLock() {
- return lock;
- }
- public Condition getCondition() {
- return cond;
- }
- public static void main(String[] args) throws InterruptedException {
- ReentrantLockTest obj = new ReentrantLockTest();
- logger.setLevel(Level.ALL);
- logger.setUseParentHandlers(true);
- Handler handler = new ConsoleHandler();
- handler.setLevel(Level.ALL);
- logger.addHandler(handler);
- Thread thread = new Thread(obj);
- thread.start();
- Thread.sleep(1000);
- Lock lock = obj.getLock();
- lock.lock();
- try {
- Condition cond = obj.getCondition();
- cond.signal();
- logger.fine("main thread notify.");
- } finally {
- lock.unlock();
- }
- thread.join();
- logger.fine("thread joined.");
- }
- @Override
- public void run() {
- lock.lock();
- try {
- lock.lock();
- try {
- try {
- logger.fine("other thread wait condition notify.");
- cond.await();
- logger.fine("other thread notified condition.");
- } catch (InterruptedException ex) {
- // ignore interrupted exception.
- }
- } finally {
- lock.unlock();
- }
- } finally {
- lock.unlock();
- }
- }
- }