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();
		}
	}
}

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值