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 }