ITPub博客

首页 > 应用开发 > Java > A Prototype of Producer-Consumer

A Prototype of Producer-Consumer

原创 Java 作者:eurt 时间:2019-04-13 11:49:24 1 删除 编辑

1  Queue.java 

package entity;
import java.util.ArrayList;
import java.util.List;
public class Queue {
	private int maxLen;
	private List<Integer> list = new ArrayList<Integer>();
	public Queue(int maxLen) {
		this.maxLen = maxLen;
	}
	
	synchronized public void push(Integer value) {
		try {
			while (list.size() == maxLen) {
				this.wait();
			}
			list.add(value);
			this.notifyAll();
			System.out.println(Thread.currentThread().getName() +
					" push=" + value + ", List=" + list.toString());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	synchronized public Integer pop() {
		Integer value = null;
		try {
			while (list.size() == 0) {
				this.wait();
			}
			value = list.get(0);
			list.remove(0);
			this.notifyAll();
			System.out.println(Thread.currentThread().getName() +
					" pop=" + value + ", List=" + list.toString());
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return value;
	}
}

2  Producer.java

package thread;
import java.util.Random;
import entity.Queue;
public class Producer extends Thread {
	private Queue queue;
	public Producer(Queue queue) {
		this.queue = queue;
	}
	@Override
	public void run() {
		while (true) {
			Random r = new Random();
			int value = r.nextInt(10) + 100;
			queue.push(value);
			try {
				Thread.sleep(r.nextInt(3)*1000);
			}catch(Exception e){}
		}
	}
	
}

3  Consumer.java

package thread;
import java.util.Random;
import entity.Queue;
public class Consumer extends Thread {
	private Queue queue;
	public Consumer(Queue queue) {
		this.queue = queue;
	}
	
	@Override
	public void run() {
		while (true) {
			queue.pop();
			
			Random r = new Random();
			try {
				Thread.sleep(r.nextInt(3)*1000);
			}catch(Exception e){}
		}
	}
}

4  Main.java

package app;
import entity.Queue;
import thread.Consumer;
import thread.Producer;
public class Main {
	public static void main(String[] args) throws InterruptedException{
		Queue myQueue = new Queue(5); // set the max length of the queue
		for (int i=0;i<6;i++) {
			new Producer(myQueue).start();
			new Consumer(myQueue).start();
		}
	}
}

5  snapshot of running

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/32498/viewspace-2641256/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2012-11-02

  • 博文量
    6
  • 访问量
    3727