生产者消费者模式--java多线程同步方法的应用

版权声明:转载或者引用本文内容请注明来源及原作者 https://blog.csdn.net/a755199443/article/details/88249488

生产者消费者模式是对java多线程的一个基础应用
我们一共设计了货物 生产者 消费者三个类
货物有商标和名称两个属性和对应的设置访问方法
生产者用于设置货物的属性
消费者用于访问并打印货物的属性
我们设置了一个生产者线程和两个消费者线程,其中生产者一次只能生产一批货物,由两个消费者争夺资源,代码如下

class Goods {
	private String brand;
	private String name;
	boolean flag;//为真即有商品,为假则没有
	//空构造器
	public Goods() {
	}
	//非空构造器
	public Goods(String brand, String name) {
		super();
		this.brand = brand;
		this.name = name;
	}
	//属性设置和获得方法
	public String getBrand() {
		return brand;
	}
	public void setBrand(String brand) {
		this.brand = brand;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	//synchronized修饰的生产方法
	public synchronized void  set(String brand,String name)  {
		if(flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		this.brand=brand;
		try {
			Thread.sleep(400);
		} catch (InterruptedException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		this.name=name;
		System.out.println(Thread.currentThread().getName()+"生产者线程生产了-----" + getBrand() + getName());
		flag = true;
		notifyAll();
		
	}
	//synchronized修饰的消费方法
	public synchronized void get() {
		
		while(!flag) {
			try {
				wait();
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName()+"消费了----" + getBrand() + getName());
		flag=false;
		notify();
	}
}
//生产者类,用于生产,即给货物Goods设定属性
public class Producter implements Runnable {
	private Goods g;

	public Producter(Goods g) {
		super();
		this.g = g;
	}

	@Override
	public void run() {
		for (int i = 0; i < 30; i++) {
			if (i % 2 == 0) {
				g.set("哇哈哈"," 矿泉水");
			} else {
				g.set("旺仔", "小馒头");
			}

			}
	}
}
//消费者类,消费货物,即访问货物的属性
class Customer implements Runnable {
	private Goods g;

	public Customer(Goods g) {
		super();
		this.g = g;
	}
	@Override
	public void run() {
		for (int i = 0; i < 30; i++) {
			g.get();
			Thread.yield();
		}
	}
}
public class 消费者生产者模式 {
	public static void main(String[] args) {
		//商品对象
		Goods g=new Goods();
		//生产者和消费者对象
		Producter p = new Producter(g);
		Customer c1 = new Customer(g);
		//线程设置
		
		Thread a = new Thread(c1,"消费者A");
		Thread b = new Thread(c1,"消费者B");
		Thread c = new Thread(p);
		a.start();
		b.start();
		c.start();
		
	}
}

猜你喜欢

转载自blog.csdn.net/a755199443/article/details/88249488