java多线程中生产者和消费者的一个实例

今天学习了Java多线程中的生产者和消费者,在这个例子中我设计了一个最大长度为10的队列,生产者产生的资源入队,消费者每次消费都会出队列。生产者每次产生一个资源后睡眠一段时间,两个消费者每次消费一个资源睡眠10ms。经过对生产者设置不同的睡眠时间可以看出竞争程度,当设置生产者休眠时间大于5ms时打印出队列长度基本都是1或者2,而休眠时间小于5ms时稳定后打印出的长度一般都是9或者10.

package 多线程;

import java.util.LinkedList;
import java.util.Queue;

public class ProducerAndComsu {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Resource resource = new Resource();
		new Thread(new Producer(resource)).start();
		new Thread(new Consumer(resource)).start();
		new Thread(new Consumer(resource)).start();
	}
}

class Producer implements Runnable {
	
	Resource source = null;

	public Producer(Resource resource) {
		// TODO Auto-generated constructor stub
		this.source = resource;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			product(source);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void product(Resource resource) throws Exception{
		
			int counter = 0;
			while (counter<1000) {
				resource.productSource("time:" + System.currentTimeMillis());
				counter++;
				Thread.sleep(4);
			}
	}

}

class Consumer implements Runnable {
	
	Resource source = null;

	public Consumer(Resource resource) {
		// TODO Auto-generated constructor stub
		this.source = resource;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			consume();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void consume() throws Exception{
		
			int counter = 0;
			while (counter<1000) {
				source.consueSource();
				counter++;
				Thread.sleep(10);
			}
	}
}

class Resource {
	
	private Queue<String> queue = null;

	public Resource() {
		// TODO Auto-generated constructor stub
		queue = new LinkedList<>();
	}

	public synchronized void productSource(String s) throws Exception {
		if (queue.size() < 10) {
			queue.offer(s);
			this.notify();
		} else {
			this.wait();
		}

	}

	public synchronized void consueSource() throws Exception {
		if (queue.size() > 0) {
			System.out.println("size:"+queue.size());
			String s = queue.poll();			
			System.out.println(s);
			this.notify();
		} else {
			this.wait();
		}
	}
}

 

发布了19 篇原创文章 · 获赞 18 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览