写一个生产者与消费者(面试)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhengzhaoyang122/article/details/82079021

一、我们可以将生产者和消费者需要的方法写在公共类中

package com.yintong.concurrent;

import java.util.LinkedList;

public class Concurrentcomm {
	//常量
	private static int MAX_VALUE = 10;
	//可以理解为缓存
	LinkedList<String> linkedList = new LinkedList<>();
	Object object = new Object();
	/*
	 * 生产者方法
	 */
	public void product() throws Exception {
		synchronized(linkedList) {
			if(MAX_VALUE == linkedList.size()) {
				System.out.println("仓库已满,【生产者】: 暂时不能执行生产任务!");
				linkedList.wait();
			}
			linkedList.push("   李四    ");
			System.out.println("【生产者】:生产了一个产品\t【现仓储量为】:" + linkedList.size());
			linkedList.notifyAll();
		}
	}
	/*
	 * 消费者方法
	 */
	public void customer() throws Exception {
		/*
		 * 根据jdk的void notifyAll()的描述,“解除那些在该对象上调用wait()方法的线程的阻塞状态。该方法只能在同步方法或同步块内部调用。
		 * 如果当前线程不是对象所得持有者,
		 * 该方法抛出一个java.lang.IllegalMonitorStateException 异常”
		 * so我们使用同一把锁
		 */
		synchronized (linkedList) {
			if(linkedList.size() == 0) {
				System.out.println("仓库无货,【消费者】: 暂时不能执行消费任务!");
				linkedList.wait();
			}
				linkedList.pop();
			System.out.println("【消费者】:消费了一个产品\t【现仓储量为】:" + linkedList.size());
			linkedList.notifyAll();
		}
	}
}

二、在main函数中调用生产者和消费者方法,并加限制即可

package com.yintong.concurrent;

/**
 * @author zzx
 * @desc 生产者与消费者
 *
 */
public class Concurrent {
//常量
	private static int MAX_VALUE = 100;
	
	public static void main(String[] args) {
		Concurrentcomm con = new Concurrentcomm();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					for (int i = 0; i < MAX_VALUE; i++) {
						Thread.sleep(0);
						con.product();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		// 消费者
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(10);
					for (int i = 0; i < MAX_VALUE; i++) {
						con.customer();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
}

三、简单的生产者与消费者模式就完成了,可以看下运行的结果

      

猜你喜欢

转载自blog.csdn.net/zhengzhaoyang122/article/details/82079021