java多线程之生产者消费者

生产者和消费者的实例代码:

//要生产的食物
public class Food{
	public String name;
	puiblic Food(String name){
		this.name = name;
	}
	@Override
	public String toString(){
		return "Food [name=" + name + "]";
	}
}

//放置食物的桌子(单例)
public class Table{
	private Table(){}
	private static Table instance = new Table();
	public static Table getInstance(){
		return instance;
	}	
	//桌子上的食物
	public Food food;
}

public class Productor implements Runnable{
	@Override
	public void run(){
		while(true){
			synchronized(""){
				//首先判断桌子上有没有食物,如果有,不需要生产,没有则生产
				if(Table.getInstance().food == null){
					//没有食物,生产
					Food food = new Food("汉堡");
					//将食物放到桌子上
					Table.getInstance().food = food;
					System.out.println(String.format("生产者【%s】生产了一个【%s】", Thread.currentThread().getName(), food.name));
					//通知消费者消费食物
					if(Table.getInstance() != null){
						"".notifyAll();
					}
				}else {
					//桌子上有食物,不需要生产
					try {
						"".wait();
					}catch (InterruptedException e){
						e.printStackTrace();
					}
				}
			}

		}
	}
}

//消费者
public class Consumer implements Runnable{
	@Override
	public void run(){
		while(true){
			synchronized(""){
				//判断桌子上有没有食物,有就消费,没有则通知生产者生产
				if(Table.getInstance().food == null){
					//没有食物,通知生产者生产
					try {
						"".wait();
					}catch (InterruptedException e){
						e.printStackTrace();
					}
				}else {
					//有食物,进行消费
					System.out.println(String.format("消费者【%s】吃了一个【%s】", Thread.currentThread().getName(), Table.getInstance().food.name));
					//消费完食物,将桌子上的食物置为空
					Table.getInstance().food == null;
					
					//消费完后通知生产者生产食物
					if(Table.getInstance().food == null){
						"".notifyAll();
					}
				}
			}
		}
	
	}
}

public class Program {
	public static void main(String[] args){
		Productor p = new Productor();
		Consumer c = new Consumer();

		Thread t1 = new Thread(p,"生产者1");
		Thread t2 = new Thread(p,"生产者2");
		Thread t3 = new Thread(p,"生产者3");
		Thread t4 = new Thread(p,"生产者4");

		Thread t5 = new Thread(c,"消费者1");
		Thread t6 = new Thread(c,"消费者1");
		Thread t7 = new Thread(c,"消费者1");
		Thread t8 = new Thread(c,"消费者1");
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		t7.start();
		t8.start();
		
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值