线程间的通信 共享数据安全问题

 1 //线程间的通信:线程的任务不同,但是线程操作的数据相同。
 2 
 3 //描述数据
 4 class Resource 
 5 {
 6     public String name;
 7     public String gender;
 8     public Resource(){}
 9 }
10 
11 //描述输入任务
12 class Input implements Runnable
13 {
14     private Resource res;
15     public Input(Resource res)
16     {
17         this.res = res;
18     }
19     public void run()
20     {
21         int i = 1;
22         while(true)
23         {
24             synchronized(res)       //加同步锁①
25             {
26                 if(i==1)
27                 {
28                     res.name = "猪小明";
29                     res.gender = "男";
30                 }
31                 else
32                 {
33                     res.name = "腿腿";
34                     res.gender = "女";
35                 }
36                 i=(++i)%2;
37             }
38         }
39     }
40 }
41 
42 //描述输出任务
43 class Output implements Runnable
44 {
45     private Resource res;
46     public Output(Resource res)
47     {
48         this.res = res;
49     }
50     public void run()
51     {
52         while(true)
53         {    
54             synchronized(res)      //加同步锁②,①处和此处为同一把锁!
55             {
56                 System.out.println(res.name + "....." + res.gender);
57             }
58         }
59     }
60 }
61 
62 class Test
63 {
64     public static void main(String[] args)
65     {
66         //创建资源
67         Resource res = new Resource();
68         //创建输入任务
69         Input input = new Input(res);
70         //创建输出任务
71         Output output = new Output(res);
72         //创建输入线程
73         Thread t1 = new Thread(input);
74         //创建输出线程
75         Thread t2 = new Thread(output);
76         //启动线程
77         t1.start();
78         t2.start();
79 
80     }
81 }

 同步的两个基本要求:

  1.  至少有两个线程
  2.  使用同一把锁

如果不使用同步,将会出现如下错误:

 

使用同步后,错误不再出现:

转载于:https://www.cnblogs.com/tzc1024/p/6031929.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值