java多线程——生产者和消费者 保证生产者先生产20个再消费

这篇博客介绍了如何在Java中实现多线程的生产者-消费者问题,确保生产者线程先生产20个产品,然后消费者线程开始消费。内容涉及线程同步和通信的机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package ls0526;

public class Run2
{
//  产品
	public static class Product
	{
		public int count=0;
	}
//  生产者
	public static class Producer implements Runnable
	{
        private Product product;
        
		public Producer(Product product)
		{
			super();
			this.product = product;
		}

		public void run()
		{
			while(true)
			{
				synchronized (product)
				{
					if(product.count<20)
					{
						product.count++;
						System.out.println(Thread.currentThread().getName()+"生产了"+product.count);
						
						try
						{
							Thread.sleep(500);
						}
						catch (InterruptedException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
			
		}
		
	}
//  消费者
	public static class Customer implements Runnable
	{
		private Product product;
		
		public Customer(Product product)
		{
			super();
			this.product = product;
		}

		public void run()
		{
			while(true)
			{
				synchronized (product)
				{
					if(product.count>0)
					{
						System.out.println(Thread.currentThread().getName()+"消费了"+product.count);
						product.count--;
						try
						{
							Thread.sleep(500);
						}
						catch (InterruptedException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	public static void main(String[] args)
	{
		Product product=new Product();
		Producer producer=new Producer(product);
		Customer customer=new Customer(product);
		Thread p1=new Thread(producer,"华为");
		Thread p2=new Thread(producer,"联想");
		Thread p3=new Thread(producer,"小米");
		Thread p4=new Thread(producer,"OPPO");
		Thread p5=new Thread(producer,"一加");
		Thread p6=new Thread(producer,"魅族");
		Thread c1=new Thread(customer,"张三");
		Thread c2=new Thread(customer,"李四");
		p1.start();
		p2.start();
		p3.start();
		p4.start();
		p5.start();
		p6.start();
		c1.start();
		c2.start();
	}
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值