Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.foo;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class LockingDemo {
- /* What I get:
- TEST 1: notify/wait
- Thread notifyB will wait...
- Thread notifyA notifies all.
- Thread notifyA: code after notifyAll()
- ... Thread notifyB is awaken.
- Thread notifyB: code after wait()
- TEST 2: signal/await
- Thread signalB will await...
- Thread signalA signals all.
- Thread signalA: code after signalAll()
- ... Thread signalB is awaken.
- Thread signalB: code after await()
- End of Test.
- */
- public static final void sleep() {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- System.err.println("Interrupted!");
- Thread.currentThread().interrupt();
- }
- }
- public static void main(String[] args) throws InterruptedException {
- final Lock monitor = new ReentrantLock(true);
- final Condition cond1 = monitor.newCondition();
- final Thread notifyA = new Thread(new Runnable() {
- public void run() {
- sleep();
- synchronized (monitor) {
- System.out.println("Thread notifyA notifies all.");
- monitor.notifyAll();
- sleep();
- System.out.println("Thread notifyA: code after notifyAll()");
- }//now notifyB can really be awaken.
- }
- });
- final Thread notifyB = new Thread(new Runnable() {
- public void run() {
- synchronized (monitor) {
- try {
- System.out.println("Thread notifyB will wait...");
- monitor.wait();
- System.out.println("... Thread notifyB is awaken.");
- sleep();
- System.out.println("Thread notifyB: code after wait()");
- } catch (InterruptedException e) {
- e.printStackTrace();
- Thread.currentThread().interrupt();
- }
- }
- }
- });
- System.out.println("TEST 1: notify/wait");
- notifyB.start();
- notifyA.start();
- notifyB.join();
- notifyA.join();
- sleep();
- System.out.println("TEST 2: signal/await");
- final Thread signalA = new Thread(new Runnable() {
- public void run() {
- sleep();
- monitor.lock();
- try {
- System.out.println("Thread signalA signals all.");
- cond1.signalAll();
- sleep();
- System.out.println("Thread signalA: code after signalAll()");
- } finally {
- monitor.unlock(); //now signalB can really be awaken.
- }
- }
- });
- final Thread signalB = new Thread(new Runnable() {
- public void run() {
- monitor.lock();
- try {
- System.out.println("Thread signalB will await...");
- cond1.await();
- System.out.println("... Thread signalB is awaken.");
- sleep();
- System.out.println("Thread signalB: code after await()");
- } catch (InterruptedException e) {
- e.printStackTrace();
- Thread.currentThread().interrupt();
- } finally {
- monitor.unlock();
- }
- }
- });
- signalB.start();
- signalA.start();
- signalB.join();
- signalA.join();
- sleep();
- System.out.println("End of Test.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement