java 22

在之前,是把生产者录入数据和消费者获取数据的所有代码都分别写在各自的类中。

这样不大好

这次把生产者和消费者部分关键代码都写入资源类中:

 1 package zl_Thread;
 2 
 3 public class Student {
 4     // 创建对象
 5     private String name;
 6     private int age;
 7     // 创建标签
 8     private boolean flag;
 9 
10     // 录入数据
11     public synchronized void  set(String name, int age) {
12       //同步方法
13         if (this.flag) {
14             // 如果存在数据, 等待
15             try {
16                 this.wait();
17             } catch (InterruptedException e) {
18                 // TODO Auto-generated catch block
19                 e.printStackTrace();
20             }
21         }
22         // 添加数据
23         this.name = name;
24         this.age = age;
25 
26         // 更改标签
27         this.flag = true;
28         // 添加了数据后,唤醒
29         this.notify();
30     }
31     //获取数据
32     public synchronized void get() {
33          //同步方法
34         if(!this.flag){
35             //如果没有数据,则等待
36             try {
37                 this.wait();
38             } catch (InterruptedException e) {
39                 // TODO Auto-generated catch block
40                 e.printStackTrace();
41             }
42         }
43         //有数据就进行处理
44         System.out.println(this.name + "--" + this.age);
45         
46         //更改标签
47         this.flag = false;
48         //唤醒
49         this.notify();
50 
51     }
52 }

然后再改变生产类和消费类的代码:

生产类:

 1 public class SetThread implements Runnable {
 2     // 生产者,录入数据
 3 
 4     private int x = 0;
 5     // 创建资源对象
 6     private Student s;
 7 
 8     public SetThread(Student s) {
 9         this.s = s;
10     }
11 
12     public void run() {
13         // 执行Student中的set类
14         while (true) {
15             if (x % 2 == 0) {
16                 s.set("张三", 23);
17             } else {
18                 s.set("李四", 24);
19             }
20             x++;
21         }
22     }
23 
24 }

消费类:

 1 public class GetThread implements Runnable {
 2     // 消费者,处理数据
 3 
 4     // 创建资源对象
 5     private Student s;
 6 
 7     public GetThread(Student s) {
 8         this.s = s;
 9     }
10 
11     public void run() {
12         // 执行Student类中的get方法
13         while (true) {
14             s.get();
15         }
16 
17     }
18 
19 }

测试类不变:

 1 public class ThreadDemo {
 2 
 3     public static void main(String[] args) {
 4 
 5         // 创建资源对象
 6         Student s = new Student();
 7 
 8         // 创建两个线程类的对象
 9         SetThread st = new SetThread(s);
10         GetThread gt = new GetThread(s);
11 
12         // 创建线程
13         Thread t1 = new Thread(st);
14         Thread t2 = new Thread(gt);
15         
16         //启动线程
17         t1.start();
18         t2.start();
19 
20     }
21 
22 }
何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5950208.html