您的位置:首页 > 其它

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

2016-11-05 10:41 435 查看
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.  使用同一把锁

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

 

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐