生产者-消费者(java并发) 博客分类: java并发 javathread
程序员文章站
2024-02-13 18:10:34
...
首先是Productor.java
接下来是仓库 CQueue.java
再者是Consumer.java
客户端 TestProductorAndConsumer .java
生产者与消费者,纯回顾一下,手写的,主要是加深印象。
待整理……
package org.iteye.bbjava.currency.pc; public class Productor implements Runnable { CQueue<String> queue; int i = 0; public Productor(CQueue<String> queue) { this.queue = queue; } @Override public void run() { while (!Thread.interrupted()) { if (queue.size() > 200) { System.out.println("仓库满了,productor 休息一下"); } else { try { System.out.println("."); Thread.sleep(500); queue.add(""+i++); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
接下来是仓库 CQueue.java
package org.iteye.bbjava.currency.pc; import java.util.LinkedList; import java.util.Queue; public class CQueue<T> { public Queue<T> queue = new LinkedList<T>(); ; public CQueue(){ } public synchronized T poll() { //consumer 从仓库取出产品 if(queue.size() <= 0 ){ try { System.out.println("仓库空了,里面没东西,consumer 休息一下 size:"+queue.size()); wait(1200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } notify(); } return queue.poll(); } public synchronized void add(T elem){ if(queue.size() >= 200){ try { System.out.println("仓库满了,容不下更多东西了,productor 休息一下 size:"+queue.size()); wait(1200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ queue.add(elem); notify(); } } public int size(){ return queue.size(); } }
再者是Consumer.java
package org.iteye.bbjava.currency.pc; import java.util.Queue; public class Consumer implements Runnable { CQueue<String> queue; @Override public void run() { while (!Thread.interrupted()) { if (queue.size() < 0) { System.out.println("仓库空了,consumer 休息"); } else { try { Thread.sleep(500); System.out.println(this.consume()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public Consumer(CQueue<String> queue) { this.queue = queue ; } public String consume(){ return this.queue.poll(); } }
客户端 TestProductorAndConsumer .java
package org.iteye.bbjava.currency.pc; public class TestProductorAndConsumer { public static void main(String []args){ CQueue<String> cq = new CQueue<String>(); System.out.println(cq.size()); Thread t2 = new Thread(new Productor(cq)); Thread t3 = new Thread(new Productor(cq)); Thread t1 = new Thread(new Consumer(cq)); Thread t4 = new Thread(new Consumer(cq)); t4.start(); t3.start(); t2.start(); t1.start(); } }
生产者与消费者,纯回顾一下,手写的,主要是加深印象。
待整理……
推荐阅读
-
生产者-消费者(java并发) 博客分类: java并发 javathread
-
java并发实践1 博客分类: java并发 javaconcurrency
-
线程同步之wait() 博客分类: java并发 javathread
-
深入理解Java内存模型(二)——重排序 博客分类: java并发
-
线程同步之wait() 博客分类: java并发 javathread
-
java并发实践1 博客分类: java并发 javaconcurrency
-
Java并发实战-私有构造函数捕获 博客分类: JAVA Java构造函数捕获
-
Java并发编程-客户端加锁机制 博客分类: JAVA 客户端加锁机制
-
Java并发编程:synchronized 博客分类: Java 多线程 synchonized
-
Java并发编程:synchronized 博客分类: Java 多线程 synchonized