java线程之生产者消费者

本文介绍了一个使用Java实现的生产者消费者模式案例。通过一个资源类Resource协调生产者和消费者的同步问题,利用synchronized关键字和wait/notify机制确保线程间的正确交互。生产者不断地生产“面包”,而消费者则消费这些产品。

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

package test;

public class ThreadTest {

	public static void main(String args[]){
		Resource r = new Resource();
		Product p = new Product(r);
		Consume c = new Consume(r);
		Thread tp = new Thread(p);
		Thread tc = new Thread(c);
		tp.start();
		tc.start();
		
	}
	
}

/**
 * 数据源
 * @author 郭胜
 *
 */
class Resource{
	private String name;
	private int count;
	boolean flag = true;//如果是真,则生产,如果是假,则消费
	
	/**
	 * 生产
	 * @param name
	 */
	public synchronized void product(String name){
		if(flag){
			this.name = name;
			++count;
			System.out.println(Thread.currentThread().getName()+"生产了"+name+"……"+count);
			flag = false;
			notify();
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 消费
	 */
	public synchronized void consume(){
		if(!flag){
			System.out.println(Thread.currentThread().getName()+"消费了……"+name+"……"+count);
			flag = true;
			notify();
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

/**
 * 生产类
 * @author 郭胜
 *
 */
class Product implements Runnable{
	
	private Resource resource;
	public Product(Resource resource){
		this.resource = resource;
	}
	
	
	public void run() {
		while(true){
			resource.product("面包");
		}
	}
	
}

class Consume implements Runnable{
	private Resource resource;
	public Consume(Resource resource){this.resource = resource;}
	
	public void run() {
		while(true){
			resource.consume();
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值