Thread(生产者和消费者)

Posted myseries

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread(生产者和消费者)相关的知识,希望对你有一定的参考价值。

package com.gdut.lang.thread;

public class ProducerAndConsumer {

	public static void main(String[] args) {
		SyncStack ss = new SyncStack();
		Producer p = new Producer(ss);
		Consumer c = new Consumer(ss);
		
		new Thread(p).start();
		new Thread(c).start();
	}

}

class WoTou {
	private int id;
	
	public WoTou(int id) {
		this.id = id;
	}
	
	public String toString() {
		return "WoTou : " + id;
	}
}

class SyncStack {
	int index = 0;
	WoTou[] arrWT = new WoTou[5];
	
	public synchronized void push(WoTou wt) {
		if ( index == arrWT.length ) { //窝头数组满了
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		arrWT[index] = wt;
		index++;
		this.notify();
	}
	
	public synchronized WoTou pop() {
		
		if ( index == 0 ) { //数组里面没窝头了
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		index--;
		this.notify();
		return arrWT[index];
		
	}
}

class Producer implements Runnable {
	SyncStack ss = null;
	public Producer(SyncStack ss) {
		this.ss = ss;
	}
	
	public void run() {
		for (int i = 0; i < 20; i++) {
			WoTou wt = new WoTou(i);
			ss.push(wt);
			System.out.println("Producer: " + wt);
			try {
				Thread.sleep((int)Math.random()*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

class Consumer implements Runnable {
	SyncStack ss = null;
	public Consumer(SyncStack ss) {
		this.ss = ss;
	}
	
	@Override
	public void run() {
		for ( int i = 0; i < 20; i++ ) {
			WoTou wt = ss.pop();
			System.out.println("Consumer: " + wt);
			try {
				Thread.sleep((int)Math.random()*1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}

  

以上是关于Thread(生产者和消费者)的主要内容,如果未能解决你的问题,请参考以下文章

SpringCloud系列十一:SpringCloudStream(SpringCloudStream 简介创建消息生产者创建消息消费者自定义消息通道分组与持久化设置 RoutingKey)(代码片段

多线程实现生产者消费者

Thread--生产者消费者

Thread--生产者消费者假死分析

java多线程同步以及线程间通信详解&消费者生产者模式&死锁&Thread.join()(多线程编程之二)

Java-Thread-生产者消费模式