wait/notify机制
- wait():在获得对象锁后主动进入等待状态让出对象锁。
- notify():同样时通知正在等待的其他线程,主动让出对象锁,但是,与 wait() 方法不同,执行 notify() 后,不会立即释放对象锁,而需要执行完 synchronize 的代码块或方法才会释放锁,所以接收通知的线程也不会立即获得锁,也需要等待执行 notify() 方法的线程释放锁后再获取锁。
应用
问题:写两个线程打印1-100,一个线程打印奇数,一个线程打印偶数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class Printer { private final int max;
private final Object lock = new Object();
private int count = 1;
public void printEven(){ print(false); }
public void printOdd(){ print(true); }
public Printer(int max){ this.max = max; }
public void print(boolean isOdd){ for (int i = 1; i <= max; i+=2) { synchronized(lock){ while (isOdd == (count%2==0)){ try { lock.wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } } System.out.println(Thread.currentThread().getName()+": "+count++); lock.notify(); } } } }
|
1 2 3 4 5 6 7 8 9 10 11
| public class Main { public static void main(String[] args) { Printer printer = new Printer(100); Thread odd = new Thread(printer::printOdd, "Odd"); Thread even = new Thread(printer::printEven, "Even"); odd.start(); even.start(); } }
|