通俗的解释JAVA wait/notify机制

时间:2023-03-09 15:22:59
通俗的解释JAVA wait/notify机制

生活中,我们常遇到需要等待的场景,例如去银行办事,在没轮到自己之前需要一直等待,但是如果需要自己每隔几秒钟就去柜台前看看状况,那肯定是种非常低效和令人恼火的体验。而实际的情况是,接待员会让您拿个号,说"请稍等一会"(wait); 当排到时,语言和大屏幕会提示"请XXX号到N号柜台办理"(notify)。

wait/notify机制也正是处理这样的场景:线程继续执行需要等待某个条件的变化,这个条件由另一个任务改变,如果一直空循环检查条件变化,是一种不良的CPU使用方式,这时候可以调用wait()将任务挂起,在其他线程调用了notify()或notifyAll()时,任务被唤醒并检查条件的变化。

这个过程中,锁的持有发生了变化。介绍wait/notify最常用的例子是生产者和消费者,设想你去饭馆吃饭,叫来服务员说,把我的宫保鸡丁端上来吧。这时候你获得了服务员的锁,在解决你的事情前,服务员不能去做别的事。(同一时间,厨师可能已经做好了宫保鸡丁,等服务员来端,但是服务员在和你说话,厨师束手无策(等待锁)。)服务员没有宫保鸡丁,只能对你说:您稍等一下,我去厨房催催。服务员调用了wait()方法,你只好释放锁,服务员回到厨房,厨师怒气冲冲的喊(获得锁),宫保鸡丁好了,端走。

下面用程序演示这一场景:

  1. public class Waiter {
  2. private String dishes = null;
  3. public synchronized String getDishes() {
  4. System.out.printf("顾客获得服务员锁%n");
  5. while(this.dishes == null) {
  6. try {
  7. System.out.printf("顾客取菜,没有菜...顾客线程等待(释放锁)%n");
  8. wait();
  9. } catch(InterruptedException ex) {
  10. ex.printStackTrace();
  11. }
  12. }
  13. String d = this.dishes;
  14. System.out.printf("顾客取走: %s%n", this.dishes);
  15. this.dishes = null;
  16. notifyAll();
  17. System.out.printf("服务员通知正在等待的线程%n");
  18. return d;
  19. }
  20. public synchronized void setDishes(String dishes) {
  21. System.out.printf("厨师获得服务员锁%n");
  22. while(this.dishes != null) {
  23. try {
  24. System.out.printf("厨师交菜,服务员已经端了另一份菜...厨师线程等待(释放锁)%n");
  25. wait();
  26. } catch(InterruptedException ex) {
  27. ex.printStackTrace();
  28. }
  29. }
  30. this.dishes = dishes;
  31. System.out.printf("厨师交菜: %s%n", this.dishes);
  32. notifyAll();
  33. System.out.printf("服务员通知正在等待的线程(顾客)%n");
  34. }
  35. public static void main(String[] args) throws InterruptedException {
  36. Waiter busy = new Waiter();
  37. for(int i = 0; i < 10; i++) {
  38. Thread consumer = new Thread() {
  39. public void run() {
  40. busy.getDishes();
  41. }
  42. };
  43. consumer.start();
  44. }
  45. Thread.sleep(100);
  46. for(int i = 0; i < 10; i++) {
  47. Thread chef = new Thread() {
  48. public void run() {
  49. String dishes = "宫保鸡丁";
  50. busy.setDishes(dishes);
  51. }
  52. };
  53. chef.start();
  54. }
  55. }
  56. }

运行结果:

  1. 顾客获得服务员锁
  2. 顾客取菜,没有菜...顾客线程等待(释放锁)
  3. 厨师获得服务员锁
  4. 厨师交菜: 宫保鸡丁
  5. 服务员通知正在等待的线程(顾客)
  6. 顾客取走: 宫保鸡丁
  7. 服务员通知正在等待的线程(厨师)

下面来说明notifyAll的作用。

修改下代码,把厨师和顾客都增加到10个

  1. public static void main(String[] args) {
  2. Waiter busy = new Waiter();
  3. for(int i = 0; i < 10; i++) {
  4. Thread consumer = new Thread() {
  5. public void run() {
  6. busy.getDishes();
  7. }
  8. };
  9. consumer.start();
  10. }
  11. for(int i = 0; i < 10; i++) {
  12. Thread chef = new Thread() {
  13. public void run() {
  14. String dishes = "宫保鸡丁";
  15. busy.setDishes(dishes);
  16. }
  17. };
  18. chef.start();
  19. }
  20. }

执行后会发现程序会陷入永久的等待无法结束,这是因为notify()方法只唤醒众多等待的线程中的一个,拿到菜后本应唤醒顾客取走,但是有可能随机唤醒了另一个等待的厨师,没有顾客能取走服务员手中的菜,这时候程序就无法继续下去了。

解决的方法有两种:

1 把notify()改成notifyAll(),唤醒所有等待的线程

2 使用Java.util.concurrent库中的Condition,把等待的线程分为厨师和顾客两个集合,代码如下:

  1. public class ConditionWaiter {
  2. private String dishes = null;
  3. private Lock lock = new ReentrantLock();
  4. private Condition conConsumer = lock.newCondition();
  5. private Condition conChef = lock.newCondition();
  6. public String getDishes() {
  7. try {
  8. lock.lock();
  9. System.out.printf("顾客获得服务员锁%n");
  10. while(this.dishes == null) {
  11. try {
  12. System.out.printf("顾客取菜,没有菜...顾客线程等待%n");
  13. conConsumer.await();
  14. } catch(InterruptedException ex) {
  15. ex.printStackTrace();
  16. }
  17. }
  18. String d = this.dishes;
  19. System.out.printf("顾客取走:%s%n", this.dishes);
  20. this.dishes = null;
  21. conChef.signal();
  22. System.out.printf("服务员通知正在等待的线程(厨师)%n");
  23. return d;
  24. } finally {
  25. lock.unlock();
  26. }
  27. }
  28. public void setDishes(String dishes) {
  29. try {
  30. lock.lock();
  31. System.out.printf("厨师获得服务员锁%n");
  32. while(this.dishes != null) {
  33. try {
  34. System.out.printf("厨师交菜,服务员已经端了另一份菜...厨师线程等待%n");
  35. conChef.await();
  36. } catch(InterruptedException ex) {
  37. ex.printStackTrace();
  38. }
  39. }
  40. this.dishes = dishes;
  41. System.out.printf("厨师交菜:%s%n", this.dishes);
  42. conConsumer.signal();
  43. System.out.printf("服务员通知正在等待的线程(顾客)%n");
  44. } finally {
  45. lock.unlock();
  46. }
  47. }
  48. public static void main(String[] args) throws InterruptedException {
  49. ConditionWaiter busy = new ConditionWaiter();
  50. for(int i = 0; i < 10; i++) {
  51. Thread consumer = new Thread() {
  52. public void run() {
  53. busy.getDishes();
  54. }
  55. };
  56. consumer.start();
  57. }
  58. Thread.sleep(100);
  59. for(int i = 0; i < 10; i++) {
  60. Thread chef = new Thread() {
  61. public void run() {
  62. String dishes = "宫保鸡丁";
  63. busy.setDishes(dishes);
  64. }
  65. };
  66. chef.start();
  67. }
  68. }
  69. }

事实上,wait/notify机制编程模型复杂也运行低效,通常我们应该采取更高级的类库实现类似场景。以下代码是使用BlockingQueue实现线程协作的示例:

    1. public class BlockingQueueWaiter {
    2. static BlockingQueue<String> queue = new ArrayBlockingQueue<>(1);
    3. public static void main(String[] args) throws InterruptedException {
    4. for(int i = 0; i < 10; i++) {
    5. Thread consumer = new Thread() {
    6. public void run() {
    7. String dishes;
    8. try {
    9. System.out.printf("顾客尝试取菜%n");
    10. dishes = queue.take();
    11. System.out.printf("顾客取走:%s%n", dishes);
    12. } catch (InterruptedException e) {
    13. e.printStackTrace();
    14. }
    15. }
    16. };
    17. consumer.start();
    18. }
    19. Thread.sleep(100);
    20. for(int i = 0; i < 10; i++) {
    21. Thread chef = new Thread() {
    22. public void run() {
    23. String dishes = "宫保鸡丁";
    24. try {
    25. System.out.printf("厨师尝试交菜%n");
    26. queue.put(dishes);
    27. System.out.printf("厨师交菜:%s%n", dishes);
    28. } catch (InterruptedException e) {
    29. e.printStackTrace();
    30. }
    31. }
    32. };
    33. chef.start();
    34. }
    35. }
    36. }