java 22 - 19 多线程之生产者和消费者的代码优化

时间:2024-04-03 23:34:32

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

这样不大好

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

 package zl_Thread;

 public class Student {
// 创建对象
private String name;
private int age;
// 创建标签
private boolean flag; // 录入数据
public synchronized void set(String name, int age) {
      //同步方法
if (this.flag) {
// 如果存在数据, 等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 添加数据
this.name = name;
this.age = age; // 更改标签
this.flag = true;
// 添加了数据后,唤醒
this.notify();
}
//获取数据
public synchronized void get() {
//同步方法
if(!this.flag){
//如果没有数据,则等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//有数据就进行处理
System.out.println(this.name + "--" + this.age); //更改标签
this.flag = false;
//唤醒
this.notify(); }
}

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

生产类:

 public class SetThread implements Runnable {
// 生产者,录入数据 private int x = 0;
// 创建资源对象
private Student s; public SetThread(Student s) {
this.s = s;
} public void run() {
// 执行Student中的set类
while (true) {
if (x % 2 == 0) {
s.set("张三", 23);
} else {
s.set("李四", 24);
}
x++;
}
} }

消费类:

 public class GetThread implements Runnable {
// 消费者,处理数据 // 创建资源对象
private Student s; public GetThread(Student s) {
this.s = s;
} public void run() {
// 执行Student类中的get方法
while (true) {
s.get();
} } }

测试类不变:

 public class ThreadDemo {

     public static void main(String[] args) {

         // 创建资源对象
Student s = new Student(); // 创建两个线程类的对象
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s); // 创建线程
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt); //启动线程
t1.start();
t2.start(); } }