浏览 927 次
锁定老帖子 主题:生产者消费者(四)
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2014-03-04
这次不使用独占锁,使用乐观锁. <pre name="code" class="java"> package ycl.learn.effective.java.thread.pc; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * 公共资源类 */ public class PublicResourceAtomic { private BlockingQueue<Product> queue = new LinkedBlockingQueue<Product>(10); public static final int MAX_RESOURCE = 20; private AtomicInteger lock = new AtomicInteger(0); private AtomicInteger index = new AtomicInteger(0); /** * 增加公共资源 */ public boolean increace() { while(true){ int s = lock.get(); int nextSeed = s+1; if(lock.compareAndSet(s, nextSeed)){//CAS 原语实现 if(isComplete()){//生产任务完成 return false; } int tindex = index.incrementAndGet(); Product p = new Product(tindex); try { queue.put(p); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread()+"increace:" + tindex); return true; } } } /** * 减少公共资源 */ public boolean decreace() { while(true){ int s = lock.get(); int nextSeed = s; if(lock.compareAndSet(s, nextSeed)){//CAS 原语实现 if (isEmpty()) { if(isComplete()){//如果消费结束,将会死锁,因为isEmpty()is true forever, 所以不管你如何notify,他始终等待,添加当wait被notify时,消费任务完成,退出。 return false; } } if(!isEmpty()){ Product p = null; try { p = queue.take(); } catch (InterruptedException e) { System.err.println(e); e.printStackTrace(); } System.out.println(Thread.currentThread()+"decreace:" + p.index); } return true; } } } public boolean isFull(){ return queue.size() == 10; } /** * 判断是否空了 */ public boolean isEmpty() { return queue.isEmpty(); } /** * 判断生产完毕 */ public boolean isComplete() { return index.get() >= MAX_RESOURCE; } class Product{ public int index; public Product(int index){ this.index = index; } } } </pre> 这里使用CAS原语. 当多个线程同时执行时,只有一个会成功. 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |