欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

生产者-消费者(java并发) 博客分类: java并发 javathread 

程序员文章站 2024-02-13 18:10:34
...
首先是Productor.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 thread