java 线程“生产/消费”模型1
2013-06-01 00:17
435 查看
/*资源类*/ public class ShareValue { private int total; public ShareValue(int total){ this.total=total; } //生产 void putValue(int value){ total+=value; } //消费资源 int getValue(int value){ if(total-value>=0){ total-=value; }else{ value=total; total=0; System.out.println("Empty!"); } return value; } //得到当前的资源值 int getNowTotal(){ return total; } } /* 生产者类 */ class Producer extends Thread { // 共享的ShareValue对象 ShareValue share; // 要增加的值 int value; public Producer(String name, ShareValue share, int value) { super(name); this.share = share; this.value = value; } public void run() { //同步share对象 ,直到当前代码块运行完毕后,share的对象锁才会释放 synchronized (share) { // 在增加之前获取share的total值 int n = share.getNowTotal(); try { sleep(100); } catch (InterruptedException e) { System.out.println(e); } share.putValue(value); // 打印增加之前的total的值n,增加的值value和增加之后total的值 System.out.println(getName() + ",Value:" + n + " Put value:" + value + " Total value:" + share.getNowTotal()); } } } /*消费者类*/ class Consumer extends Thread{ //共享的ShareValue对象 ShareValue share; //要减少的值 int value; public Consumer(String name,ShareValue share, int value) { super(name); this.share = share; this.value = value; } public void run(){ //同步share对象,直到当前代码运行完毕后,share的对象锁才会释放 synchronized (share) { //在减少之前,获取share对象的total值 int n=share.getNowTotal(); try { sleep(100); } catch (InterruptedException e) { System.out.println(e); } share.getValue(value); //打印减少之前的total的值n,减去的值value和减少之后total的值 System.out.println(getName()+",Value:"+n+" Get value:"+value+" Total value:"+share.getNowTotal()); } } } /* 测试主类 */ public class TestDemo { public static void main(String[] args) { ShareValue share=new ShareValue(0); Producer producer1=new Producer("producer1", share, 100); Producer producer2=new Producer("producer2",share,200); Consumer consumer=new Consumer("consumer", share, 50); producer1.start(); producer2.start(); consumer.start(); } } /* 通过对share对象的锁定来达到同步的目的 */
相关文章推荐
- Java学习札记之线程模型——生产消费模型
- java线程“生产/消费”模型2
- Java中线程知识总结(生产消费模型)
- java生产者消费者模型(线程协作)
- 生产/消费模型的java实现
- java生产消费线程小例子
- 线程并发集合实现java生成消费模型(ArrayBlockingQueue和ConcurrentMap)
- 生产/消费模型的java实现
- 深度剖析java线程安全|内存模型|生产消费者模式|
- 线程交互:生产消费模型
- Java环形缓冲区+生产消费模型及同步开销测试
- 【JAVA】wait和notify用法,附生产/消费模型
- java线程的同步中notify和wait方法之生产消费实例讲解
- JAVA 多线程制作大球吃小球 一、实现球的自动生成及运动 生产消费模型
- java学习9:生产和消费问题,先生产才能消费,线程间通信与等待
- 并发队列ConcurrentLinkedQueue和阻塞队列LinkedBlockingQueue用法 在Java多线程应用中,队列的使用率很高,多数生产消费模型的首选数据结构就是队列(先进先出)。
- java线程之生产与消费
- java线程同步----生产消费
- 线程_生产消费模型
- 生产/消费模型的java实现