一个线程同步的例子..

 1 class Info {
 2      
 3     public String getName() {
 4         return name;
 5     }
 6  
 7     public void setName(String name) {
 8         this.name = name;
 9     }
10  
11     public int getAge() {
12         return age;
13     }
14  
15     public void setAge(int age) {
16         this.age = age;
17     }
18  
19     public synchronized void set(String name, int age){
20         this.name=name;
21         try{
22             Thread.sleep(100);
23         }catch (Exception e) {
24             e.printStackTrace();
25         }
26         this.age=age;
27     }
28      
29     public synchronized void get(){
30         try{
31             Thread.sleep(100);
32         }catch (Exception e) {
33             e.printStackTrace();
34         }
35         System.out.println(this.getName()+"<===>"+this.getAge());
36     }
37     private String name = "Rollen";
38     private int age = 20;
39 }
40  
41 /**
42  * 生产者
43  * */
44 class Producer implements Runnable {
45     private Info info = null;
46  
47     Producer(Info info) {
48         this.info = info;
49     }
50  
51     public void run() {
52         boolean flag = false;
53         for (int i = 0; i < 25; ++i) {
54             if (flag) {
55                  
56                 this.info.set("Rollen", 20);
57                 flag = false;
58             } else {
59                 this.info.set("ChunGe", 100);
60                 flag = true;
61             }
62         }
63     }
64 }
65  
66 /**
67  * 消费者类
68  * */
69 class Consumer implements Runnable {
70     private Info info = null;
71  
72     public Consumer(Info info) {
73         this.info = info;
74     }
75  
76     public void run() {
77         for (int i = 0; i < 25; ++i) {
78             try {
79                 Thread.sleep(100);
80             } catch (Exception e) {
81                 e.printStackTrace();
82             }
83             this.info.get();
84         }
85     }
86 }
87  
88 /**
89  * 测试类
90  * */
91 class hello {
92     public static void main(String[] args) {
93         Info info = new Info();
94         Producer pro = new Producer(info);
95         Consumer con = new Consumer(info);
96         new Thread(pro).start();
97         new Thread(con).start();
98     }
99 }

 

转载于:https://www.cnblogs.com/Akishimo/archive/2013/03/17/2964549.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值