首页 > 其他 > 详细

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

时间:2014-03-05 21:41:30      阅读:402      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
 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 }
bubuko.com,布布扣

线程间通信--等待唤醒机制,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/linson0116/p/3583006.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!