java多线程生产者与消费者事例代码

package org.yang;

public class Factory {
	public static final int MAX = 10;
	
	private int current;
	
	public int getCurrent() {
		return current;
	}

	public synchronized void product(int number, String name)
	{
		while ( this.current + number > MAX)
		{
			try
			{
				this.wait();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		this.current += number;
		System.out.println(name + "已經生產了:" + number +"個" + " 一共有:" + this.current);
		this.notifyAll();
	}
	
	public synchronized void dec(int num, String name)
	{
		while(this.current-num < 0)
		{
			try
			{
				this.wait();
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}
		this.current -= num;
		System.out.println(name + "已經消費了:" + num +"個" + " 還剩有:" + this.current);
		this.notifyAll();
	}
}



package org.yang;

public class Customer {
	
	public static void main(String[] args) {
		Factory factory = new Factory();
			new Thread(new Shengchang(10, factory)).start();
			new Thread(new Shengchang(1, factory)).start();
			new Thread(new Shengchang(2, factory)).start();
			new Thread(new Shengchang(3, factory)).start();
			new Thread(new Shengchang(4, factory)).start();
			
			new Thread(new XiaoFei(5, factory)).start();
			new Thread(new XiaoFei(6, factory)).start();
			new Thread(new XiaoFei(7, factory)).start();
			new Thread(new XiaoFei(8, factory)).start();
			new Thread(new XiaoFei(9, factory)).start();
	}
	
	static class Shengchang implements Runnable
	{
		private Factory factory;
		int number;
		public Shengchang(int number, Factory factory) {
			this.number = number;
			this.factory = factory;
		}
		@Override
		public void run() {
			while(true)
				factory.product(number, Thread.currentThread().getName());
		}
	}
	
	static class XiaoFei implements Runnable
	{
		private Factory factory;
		int num;
		public XiaoFei(int num, Factory factory) {
			this.factory = factory;
			this.num = num;
		}
		@Override
		public void run() {
				while(true)
				factory.dec(num, Thread.currentThread().getName());
		}
		
	}
}

你可能感兴趣的:(多线程,消费者与生产者)