• wait()、notify/notifyAll() 方法是Object的本地final方法,无法被重写。
  • wait()使当前线程阻塞,前提是 必须先获得锁,一般配合synchronized 关键字使用,即,一般在synchronized 同步代码块里使用 wait()、notify/notifyAll() 方法。
  • 当线程执行wait()方法时候,会释放当前的锁,然后让出CPU,进入等待状态。
  • 只有当 notify/notifyAll() 被执行时候,才会唤醒一个或多个正处于等待状态的线程,然后继续往下执行,直到执行完synchronized 代码块的代码或是中途遇到wait() ,再次释放锁。
  • 也就是说,notify/notifyAll() 的执行只是唤醒沉睡的线程,而不会立即释放锁,锁的释放要看代码块的具体执行情况。所以在编程中,尽量在使用了notify/notifyAll() 后立即退出临界区,以唤醒其他线程让其获得锁
  • wait() 需要被try catch包围,以便发生异常中断也可以使wait等待的线程唤醒。
  • notify 和wait 的顺序不能错,如果A线程先执行notify方法,B线程在执行wait方法,那么B线程是无法被唤醒的。


notify 和 notifyAll的区别

notify方法只唤醒一个等待(对象的)线程并使该线程开始执行。所以如果有多个线程等待一个对象,这个方法只会唤醒其中一个线程,选择哪个线程取决于操作系统对多线程管理的实现。
image.png
notifyAll 会唤醒所有等待(对象的)线程,尽管哪一个线程将会第一个处理取决于操作系统的实现。如果当前情况下有多个线程需要被唤醒,推荐使用notifyAll 方法。比如在生产者-消费者里面的使用,每次都需要唤醒所有的消费者或是生产者,以判断程序是否可以继续往下执行。
image.png

生产者消费者

  1. public class Test {
  2. public static void main(String[] args) {
  3. Product product = new Product();
  4. Producer producer = new Producer(product);
  5. Consumer consumer = new Consumer(product);
  6. new Thread(producer).start();
  7. new Thread(consumer).start();
  8. }
  9. }
  10. class Producer implements Runnable {
  11. private Product product;
  12. public Producer(Product product) {
  13. this.product = product;
  14. }
  15. @Override
  16. public void run() {
  17. synchronized (product) {
  18. while (true) {
  19. if (product.num >= 5) {
  20. try {
  21. product.wait();
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. product.num++;
  27. System.out.println("生产成功,商品总数:" + product.num);
  28. try {
  29. TimeUnit.SECONDS.sleep(1);
  30. } catch (InterruptedException e) {
  31. e.printStackTrace();
  32. }
  33. product.notifyAll();
  34. }
  35. }
  36. }
  37. }
  38. class Consumer implements Runnable {
  39. private Product product;
  40. public Consumer(Product product) {
  41. this.product = product;
  42. }
  43. @Override
  44. public void run() {
  45. synchronized (product) {
  46. while (true) {
  47. if (product.num <= 0) {
  48. try {
  49. product.wait();
  50. } catch (InterruptedException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. product.num--;
  55. System.out.println("消费成功,商品总数为:" + product.num);
  56. try {
  57. TimeUnit.SECONDS.sleep(1);
  58. } catch (InterruptedException e) {
  59. e.printStackTrace();
  60. }
  61. product.notifyAll();
  62. }
  63. }
  64. }
  65. }
  66. class Product {
  67. int num = 0;
  68. }