A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

在实现线程间通信时抱错java.lang.IllegalMonitorStateException
有两个线程类GetThread和SetThread代码如下:
package cn.itcast_01_Tread_Ticket_2_tongxing;
public class SetThread implements Runnable {
Student s;
int x = 0;
SetThread(Student s) {
  this.s = s;
}
@Override
public void run() {
  while (true) {
   s.lock.lock();
   if (s.flag) {
    try {
     s.lock.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   if (x % 2 == 0) {
    s.name = "张三";
    s.age = 23;
   } else {
    s.name = "李四";
    s.age = 26;
   }
   x++;
   s.flag = true;
   s.lock.notify();   //33行
   s.lock.unlock();
  }
}
}

package cn.itcast_01_Tread_Ticket_2_tongxing;
public class GetThread implements Runnable {
Student s;
GetThread(Student s) {
  this.s = s;
}
@Override
public void run() {
  while (true) {
   s.lock.lock();
   if (!s.flag) {
    try {
     s.lock.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
   System.out.println(s.name + "----" + s.age);
   s.flag = false;
   s.lock.notify();
   s.lock.unlock();
  }
}
}

报错
Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at cn.itcast_01_Tread_Ticket_2_tongxing.SetThread.run(SetThread.java:33)
at java.lang.Thread.run(Thread.java:745)


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马