本帖最后由 枫儿 于 2013-10-10 16:37 编辑
- class rec//共享资源
- {
- String name;
- String age;
- boolean flag=false;
- }
- class Input implements Runnable//往资源里传值
- {
- private rec r;
- Input(rec r)
- {
- this.r=r;
- }
- public void run()
- {
- int x=0;
- while (true)
- {
- synchronized(r)
- {
- if (r.flag)
- try{wait();}catch(Exception e){}
- if(x==0)
- {
- r.name="make";
- r.age="Man";
- }
- else
- {
- r.name="扣扣";
- r.age="女女女";
- }
- x=(x+1)%2;
- r.flag=true;
- r.notify();
- }
- }
- }
- }
- class out implements Runnable//打印资源里的值
- {
- private rec r;
- out(rec r)
- {
- this.r=r;
- }
- public void run()
- {
- while (true)
- {
- synchronized(r)
- {
- if(!r.flag)
- try{wait();}catch(Exception e){}
- System.out.println(r.name+"...."+r.age);
- r.flag=false;
- r.notify();
- }
- }
- }
- }
- class dxctx1
- {
- public static void main(String[] args)
- {
- rec r = new rec();
- Input in = new Input(r);
- out o = new out(r);
- Thread t1 = new Thread(in);
- Thread t2 = new Thread(o);
- t1.start();
- t2.start();
- }
- }
复制代码 上面代码为啥运行时还是一片、一片的打印呢???
|
|