本帖最后由 FFF 于 2013-11-8 22:46 编辑
Wait没有明确的指向。Wait,你要wait谁,要说清楚。只要把Wait()前面加上个this就可以了!- try{this.wait();}catch(Exception e){}//Wait改
复制代码 贴上我的代码,给你参考一下!- package temp;
- class Res
- {
- private String name;
- private String sex;
- boolean flag= false ;
- public synchronized void ste(String name,String sex)
- {
- if(flag)
- try{this.wait();}catch(Exception e){}
- this.name=name;
- this.sex=sex;
- flag=true;
- this.notify();
- }
- public synchronized void out()
- {
- if(!flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(name+"Is"+sex);
- flag=false;
- this.notify();
- }
- }
- class Input implements Runnable
- {
- private Res r;
- Input(Res r)
- {
- this.r = r;
- }
- public void run()
- {
- int x= 0;
- int close = 0;
- while(close<20)
- {
- if(x==0)
- r.ste("贝克","Man");
- else
- r.ste("安吉","lady");
- x= (x+1)%2;
- close++;
- }
- }
- }
- class Output implements Runnable
- {
- private Res r;
- private int close1=0;
- Output(Res r)
- {
- this.r=r;
- }
- public void run()
- {
- while(close1<20)
- {
- r.out();
- close1++;
- }
- }
- }
- public class Temp10_24多线程通信_唤醒机制 {
- public static void main(String[] args)
- {
- Res r = new Res();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
- /*
- Input in = new Input(r);
- Output ou = new Output(r);
-
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(ou);
-
- t1.start();
- t2.start();
- */
- }
- }
复制代码 |