黑马程序员技术交流社区

标题: 求解同步代码块,等待唤醒机制问题 [打印本页]

作者: SkyBlack    时间: 2016-7-10 23:49
标题: 求解同步代码块,等待唤醒机制问题
  1. <p>class Print {
  2.         private int flag = 1;
  3.         public void print1() throws InterruptedException {
  4.                 synchronized(this) {
  5.                         if (flag != 1) {
  6.                                 this.wait();
  7.                         }
  8.                         System.out.print("黑");
  9.                         System.out.print("马");
  10.                         System.out.print("程");
  11.                         System.out.print("序");
  12.                         System.out.print("员");
  13.                         System.out.println();
  14.                         flag = 2;
  15.                         this.notify();
  16.                 }
  17.         }
  18.        
  19.         public void print2() throws InterruptedException {
  20.                 synchronized(this) {
  21.                         if (flag != 2) {
  22.                                 this.wait();
  23.                         }
  24.                         System.out.print("传");
  25.                         System.out.print("智");
  26.                         System.out.print("播");
  27.                         System.out.print("客");
  28.                         System.out.println();
  29.                         flag = 1;
  30.                         this.notify();
  31.                 }
  32.         }
  33. }</p><p>
  34. </p><p>为什么用类名.class锁会出错啊</p><p>错误如下:</p><p>java.lang.IllegalMonitorStateException
  35. 黑马程序员
  36. at java.lang.Object.notify(Native Method)
  37. at com.heima.test.Print.print2(Test_Wait.java:68)
  38. at com.heima.test.Test_Wait$2.run(Test_Wait.java:26)
  39. java.lang.IllegalMonitorStateException
  40. at java.lang.Object.notify(Native Method)
  41. at com.heima.test.Print.print1(Test_Wait.java:53)
  42. at com.heima.test.Test_Wait$1.run(Test_Wait.java:14)
  43. java.lang.IllegalMonitorStateException传智播客</p>
复制代码



作者: zhangwenjin    时间: 2016-7-10 23:53
我表示看不懂
作者: SkyBlack    时间: 2016-7-11 10:55
zhangwenjin 发表于 2016-7-10 23:53
我表示看不懂

学到这就懂了,表示我知道原因了
作者: Mr.Wu    时间: 2016-7-11 11:32
你这是用的this锁呀,假如是继承的Thread创建的多线程会产生多个对象。锁就会失效,建议使用实现Runnable接口时使用this锁
作者: SkyBlack    时间: 2016-7-20 14:07
谢谢啦~




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2