欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

生产者消费者2

程序员文章站 2022-12-20 19:12:33
1功能生产者 :向产品容器中添加产品对象消费者 :从产品容器中移除产品对象容器满了,生产者线程进入等待池,调用wait()容器空了,消费者线程调用notify()2 类package com.lidongwei.mythread.test;import java.util.LinkedList;public class ProducerConsumer {public static void main(String[] args) {LinkedList

1功能

生产者 :向产品容器中添加产品对象
消费者 :从产品容器中移除产品对象
容器满了,生产者线程进入等待池,调用wait()
容器空了,消费者线程调用notify()

2 类

package com.lidongwei.mythread.test;

import java.util.LinkedList;

public  class ProducerConsumer {

	public static void main(String[] args) {
		LinkedList<Producer> producers = new LinkedList<>();
		Producer producer = new Producer();
		producer.setProducers(producers);
		Thread threadP = new Thread(producer);
		Consumer consumer  = new Consumer();
		consumer.setProducers(producers);
		Thread threadC = new Thread(consumer);
		
		threadP.start();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		threadC.start();
	}
}
/*
 * 每两秒生产一个产品,如果满了,就wait
 */
class Producer implements Runnable{
	private LinkedList<Producer> producers;

	public void setProducers(LinkedList<Producer> producers) {
		this.producers = producers;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		
			while(true)
			{
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(producers.size() == 5)
				{
					try {
						System.out.println("停止生产,当前产品数:" + producers.size());
						synchronized (producers) {
							producers.wait();
						}
						System.out.println("开始生产,当前产品数:" +  producers.size());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				else
				{
					synchronized ( producers) {
						producers.add(new Producer());
					}
					System.out.println("生产了一个,当前产品数:" + producers.size());
				}
			}
		
			
	}
	
}
/*
 * 每两秒生产一个产品,如果满了,就wait
 */
class Consumer implements Runnable{
	private LinkedList<Producer> producers;
	

	public void setProducers(LinkedList<Producer> producers) {
		this.producers = producers;
	}


	@Override
	public void run() {
		// TODO Auto-generated method stub
			while(true)
			{
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if( producers.size() == 0)
				{
					synchronized ( producers) {
						 producers.notify();
					}
					System.out.println("通知生产线,当前产品数:" +  producers.size());
				}
				else
				{
					synchronized ( producers) {
						producers.remove(0);
					}
					System.out.println("消费了一个,当前产品数:" + producers.size());
				}
			}
		}
}
class Produce {
}

执行结果
生产者消费者2

本文地址:https://blog.csdn.net/qq_23996885/article/details/109648647