码迷,mamicode.com
首页 > 其他好文 > 详细

并发同步与锁

时间:2015-03-14 21:49:30      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

1.一个生产者和一个消费者。
存在资源竞争情况:1).生产者和消费者同时访问fuilt store,当时fuilt store库存为0时,生产者生产一个产品,但未修改库存数量时,消费者这时访问fuilt store发现库存数量为0,无法购买产品;当fuilt store库存为100时,消费者购买一个产品后,未来得及修改库存数量,生产者这时访问fuilt store发现库存满了,不在生产产品。  

这种资源竞争的情况,还不算糟糕,虽然造成了某一次的判断错误,但并没有影响整体业务功能。

class  FuiltStore {
	public int curFuiltNum = 0;
	public boolean increase()
	{
		if (curFuiltNum < 100) {
		    this.curFuiltNum++;
		    return true;
		}
		return false;
	}
	public boolean decrease()
	{
		if (curFuiltNum > 0) {
		    this.curFuiltNum--;
		    return true;
		}
		return false;
	}
}

class FuiltWorkerTom implements Runnable{
	private FuiltStore fuiltStore;
	private int stockNum = 0;
	public FuiltWorkerTom(FuiltStore fuiltStore)
	{
		this.fuiltStore = fuiltStore;
	}
	public boolean stockFuilt() {
		if (this.fuiltStore.increase())
		{
			System.out.println("stock");
			return true;
		}
		return false;
	}
	@Override
	public void run() {
		while (this.stockNum < 100) {
			if (this.stockFuilt()) {
				this.stockNum++;
				Thread.yield();
			}
		}
	}
}
class FuiltBuyerMary implements Runnable{
	private FuiltStore fuiltStore;
	private int buyNum = 0;
	public FuiltBuyerMary(FuiltStore fuiltStore)
	{
		this.fuiltStore = fuiltStore;
	}
	public boolean buyFuilt() {
		if (this.fuiltStore.decrease()) {
			System.out.println("buy");
			return true;
		}
		return false;
	}
	@Override
	public void run() {
		while (this.buyNum < 100) {
			if (this.buyFuilt()) {
				this.buyNum++;
			    Thread.yield();
			}
		}
	}
}
public class MainThread {

	public static void main(String[] args) {
		FuiltStore fuiltStore = new FuiltStore();
        Thread fuiltWorkerTom = new Thread(new FuiltWorkerTom(fuiltStore));
        fuiltWorkerTom.start();
        Thread fuiltBuyerMary = new Thread(new FuiltBuyerMary(fuiltStore));
        fuiltBuyerMary.start();
        try {
			fuiltWorkerTom.join();
	        fuiltBuyerMary.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println(fuiltStore.curFuiltNum);  
	}

}

并发同步与锁

标签:

原文地址:http://blog.csdn.net/guoguo11191/article/details/44263007

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!