下面是代码--->- package yting.day11.thread;
- public class ThreadCommunication {
- public static void main(String[] args) {
- Resource r = new Resource();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
- }
- }
- class Resource {
- String name;
- String sex;
- boolean flag = false;
- }
- class Input implements Runnable {
- private Resource r;
- public Input(Resource r) {
- super();
- this.r = r;
- }
- @Override
- public void run() {
- int f = 0;
- while (true) {
- synchronized (r) {
- if(r.flag){
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- if (f == 0) {
- r.name = "zhangsan";
- r.sex = "男";
- } else {
- r.name = "lili";
- r.sex = "女";
- }
- f = (f + 1) % 2;
-
- r.flag = true;
- notify();
- }
- }
- }
- }
- class Output implements Runnable {
- private Resource r;
- public Output(Resource r) {
- super();
- this.r = r;
- }
- @Override
- public void run() {
- while (true) {
- synchronized (r) {
- if(!r.flag){
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(r.name + "..." + r.sex);
-
- r.flag = false;
- notify();
- }
- }
- }
- }
复制代码 下面是运行结果--->- Exception in thread "Thread-0" zhangsan...男
- java.lang.IllegalMonitorStateException
- at java.lang.Object.notify(Native Method)
- at yting.day11.thread.Input.run(ThreadCommunication.java:49)
- at java.lang.Thread.run(Thread.java:662)
- Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
- at java.lang.Object.notify(Native Method)
- at yting.day11.thread.Output.run(ThreadCommunication.java:78)
- at java.lang.Thread.run(Thread.java:662)
复制代码 一直抱这个异常,怎么回事啊?坐等大神指导、、、谢了先!
|
|