消费者与生产者必须一对一,消费者消费完了通知生产者,生产者生产完了通知消费者。
可以先定义一个共同的属性static String str;再用volatile来修饰volatile static String str;
volatile 修饰的属性为线程可见性属性
通过有参构造方法传入同一个目标
实现Runnable接口或者继承Thread类后重写run方法→用到synchronized方法:
属性类↓
public class Shuxing {
volatile static String str;
}
生产者↓
public class Producer implements Runnable{
Shuxing shuxing;
//通过有参构造传入对象
public Producer(Shuxing shuxing) {
super();
this.shuxing = shuxing;
}
public void run() {
//设置死循环
while (true) {
//synchronized锁定的对象是自定义的shuxing
synchronized (shuxing) {
//判断当shuxing的str里面有值那么该程序进入等待状态,由消费者先消费
if (shuxing.str!=null) {
try {
shuxing.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//生产者生产东西给str
shuxing.str=System.currentTimeMillis()+"";
System.out.println("生产者已生产"+shuxing.str);
//生产完了,唤醒消费者
shuxing.notify();
}
}
}
}
}
消费者↓
public class Customer implements Runnable{
Shuxing shuxing;
//通过有参构造传入对象
public Customer(Shuxing shuxing) {
super();
this.shuxing = shuxing;
}
public void run() {
while (true) {
//synchronized锁定的对象是自定义的shuxing
synchronized (shuxing) {
//判断当shuxing的str里面没值那么该程序进入等待状态,由生产者先生产
if (shuxing.str==null) {
try {
shuxing.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//消费者开始消费,清空str的值
shuxing.str=null;
System.out.println("消费者已消费"+shuxing.str);
//消费者已消费完毕,唤醒生产者
shuxing.notify();
}
}
}
}
}
测试类↓
public class Text1 {
public static void main(String[] args) {
//实例化对象
Shuxing sx=new Shuxing();
//通过构造方法传入同一个对象
Thread t1=new Thread(new Producer(sx));
Thread t2=new Thread(new Customer(sx));
//开启线程
t1.start();
t2.start();
}
}
线程:消费者与生产者案例
最新推荐文章于 2023-05-09 10:24:54 发布