线程间通信--等待唤醒机制

 1 class Demo4 
 2 {
 3     public static void main(String[] args) 
 4     {
 5         Res r = new Res();
 6         Input in  = new Input(r);
 7         Output out  = new Output(r);
 8         new Thread(in).start();
 9         new Thread(out).start();
10     }
11 }
12 class Res
13 {
14     String name;
15     int age;
16     boolean flag = false;
17 }
18 class Input implements Runnable
19 {
20     Res r;
21     Input(Res r){this.r = r;}
22     public void run(){
23         while(true){
24             synchronized(r){
25                 if(r.flag == true){
26                     try
27                     {
28                         r.wait();
29                     }
30                     catch (InterruptedException e)
31                     {
32                     }
33                 }else{
34                     r.name = "kobe";
35                     r.age = (int)(Math.random()*10);
36                     r.flag = true;
37                     r.notify();
38                 }
39             }
40         }
41     }
42 }
43 class Output implements Runnable
44 {
45     Res r;
46     Output(Res r){this.r = r;}
47     public void run(){
48         while(true){
49             synchronized(r){
50                 if(r.flag == true){
51                     System.out.println(r.name + "::"+ r.age);
52                     r.flag = false;
53                     r.notify();
54                 }else{
55                     try
56                     {
57                         r.wait();
58                     }
59                     catch (InterruptedException e)
60                     {
61                     }
62                 }
63             }
64         }
65     }
66 }

 

posted @ 2014-03-05 18:04  一路向北中  阅读(144)  评论(0)    收藏  举报