多线程生产、消费

生产者:

public class GoodsAdd implements Runnable{
	
	private  TestEntity i;
	public GoodsAdd(TestEntity i) {
		this.i = i;
	}
	public void add() {
		synchronized (i) {
			if(i.getInteger()==null) {
				i.setInteger(0);
			}
			i.setInteger(i.getInteger()+1);
			System.out.println(Thread.currentThread().getName()+i.getInteger());
			i.notify();
		}
	}
	@Override
	public void run() {
		add();
	}
}

消费者:

public class GoodsDelete implements Runnable{

	private TestEntity i;
	public GoodsDelete(TestEntity i) {
		this.i = i;
	} 
	public void delete() {
		synchronized (i) {
			if(i.getInteger()==null){ //确保消费者和生产者人数一样,把线程阻塞
				try {
					i.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			while( i.getInteger()<=0) {
				try {
					i.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			i.setInteger(i.getInteger()-1);
			System.out.println(Thread.currentThread().getName()+i.getInteger());
		}
	}
	@Override
	public void run() {
		delete();
	}
}

生产的数量:
 

public class Test {
	
	public static void main(String[] args) {
		
		TestEntity count = new TestEntity();
		
		GoodsAdd pin = new GoodsAdd(count);
		GoodsDelete pinDelete = new GoodsDelete(count);
		
		for (int i = 0; i < 100; i++) {
			Thread add = new Thread(pin,"add: ");
			Thread delete = new Thread(pinDelete,"delete: ");
			delete.start();
			add.start();
		}
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(count.getInteger());
	}
}

测试类:

public class Test {
	
	public static void main(String[] args) {
		
		TestEntity count = new TestEntity();
		
		GoodsAdd pin = new GoodsAdd(count);
		GoodsDelete pinDelete = new GoodsDelete(count);
		
		for (int i = 0; i < 100; i++) {
			Thread add = new Thread(pin,"add: ");
			Thread delete = new Thread(pinDelete,"delete: ");
			delete.start();
			add.start();
		}
		
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(count.getInteger());
	}
}

为什么生产的商品数要声明到一个类里面呢?

      如果直接用integer++的话,notify()方法会报错,这是因为synchronized关键字锁的对象和notify()调用的对象不是同一个。

有错的地方还望各位大侠指教。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值