- class ZiYuan
- {
- private String name;
- private String sex;
- private boolean flag;
- public void set(String name,String sex)
- {
- if(flag)
- try{this.wait();}catch(Exception e){ }
- this.name=name;
- this.sex=sex;
- this.flag=true;
- this.notify();
- }
- public void ShuChu()
- {
- if(!flag)
- try{this.wait();}catch(Exception e){ }
- System.out.println(name+"====="+sex);
- this.flag=false;
- this.notify();
- }
- }
- class Input implements Runnable
- {
- private ZiYuan r;
- Input(ZiYuan r)
- {
- this.r=r;
- }
- public void run()
- {
- int x=0;
- while(true)
- {
- if(x==0)
- r.set("iron man","male");
- else
- r.set("朴信惠","女");
- x=(x+1)%2;
- }
- }
- }
- class Output implements Runnable
- {
- private ZiYuan r;
- Output(ZiYuan r)
- {
- this.r=r;
- }
- public void run()
- {
- while(true)
- {
-
- r.ShuChu();
- }
- }
- }
- class TongXun02
- {
- public static void main(String[] args)
- {
- ZiYuan r =new ZiYuan();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
-
- }
- }
复制代码
出现的提示是:Exception in thread "Thread-0" iron man=====male
Exception in thread "Thread-1" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at ZiYuan.set(TongXun02.java:14)
at Input.run(TongXun02.java:41)
at java.lang.Thread.run(Thread.java:745)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at ZiYuan.ShuChu(TongXun02.java:23)
at Output.run(TongXun02.java:62)
at java.lang.Thread.run(Thread.java:745)
|