简单生产者消费者模式

本文深入探讨了线程之间的基本通信机制,通过生产者-消费者模式的实例代码,详细解析了如何使用Java的synchronized关键字和wait/notify方法实现线程间的同步与通信。文章通过具体的生产者和消费者类的实现,展示了如何在多线程环境中解决资源竞争问题。

知识点:线程基本通信

生产者:
package com.fengunion.dxc.pc;

import java.util.List;

public class Producer implements Runnable {

private List<String> list;

public Producer(List<String> list) {
this.list = list;
}

@Override
public void run() {
while (true){
synchronized (list){
if(list.size()==1){
System.out.println("队列已满....");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add("1");
list.forEach(x ->{
System.out.println("生产数据:"+x);
});
list.notify();
}
}
}
}
消费者:
package com.fengunion.dxc.pc;

import java.util.List;

public class Consumer implements Runnable {
private List<String> list;
public Consumer(List<String> list){
this.list=list;
}
@Override
public void run() {
while (true){
synchronized (list){
if(list.size()==0){
System.out.println("队列为空");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
list.forEach(x ->{
System.out.println("消费数据:"+x);
});
list.remove("1");
list.notify();
}
}
}
}
测试:
public static void main(String[] args) {
List<String> list=new ArrayList<>();
Producer p=new Producer(list);
Consumer c = new Consumer(list);
Thread thread = new Thread(p);
Thread thread1 = new Thread(c);
thread.start();
thread1.start();

}

转载于:https://www.cnblogs.com/coderdxj/p/9708074.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值