package lock;
import java.util.ArrayList;
import java.util.List;
/**
* 多线程实现生产者与消费者
* 生产一个消费一个
*/
public class ProducerAndConsumer {
public static void main(String[] args) {
//创建一个仓库
List warehouse = new ArrayList();
//生产者
Thread producer = new Thread(new Producer(warehouse));
producer.setName("生产者");
//消费者
Thread consumer = new Thread(new Consumer(warehouse));
consumer.setName("消费者");
//启动线程
producer.start();
consumer.start();
}
}
//生产者
class Producer implements Runnable{
private List list ;
public Producer(List list) {
this.list = list;
}
@Override
public void run() {
while (true){
synchronized (list){
//有产品进入等待状态
if (this.list.size() > 0){
try {
list.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//无产品开始生产
Object producer = new Object();
System.out.println(Thread.currentThread().getName()+"---->"+producer);
list.add(producer);
//唤醒消费者线程
list.notifyAll();
}
}
}
}
//消费者
class Consumer implements Runnable{
private List list;
public Consumer(List list) {
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
//无产品进入等待状态
if (list.size() == 0){
//释放锁 进入等待状态
try {
list.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
//消费结束
System.out.println(Thread.currentThread().getName()+ "---->" +list.get(0));
list.remove(0);
//唤醒生产者
list.notifyAll();
}
}
}
}
生产者与消费者
于 2023-10-31 17:07:58 首次发布