java实现的生产者和消费者问题-涉及线程同步与通信

1:共享数据类

 

package com.pb.consumerandproducer;

public class ShareData {
	private char c;  //代表仓库里的产品
	private boolean isProduced = false;  //是否还有供消费者消费的产品
	
	public synchronized void putData(char c) {  //生产者生产产品放入仓库
		if(isProduced) { //仓库中还有未消费的产品
			System.out.println("仓库中还有未消费的产品,生产者等待");
			try {
				wait();  //将线程挂起
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.c = c;
		isProduced = true;  //标记为已生产
		notify();   //通知消费者消费,激活消费者线程
		System.out.println("生产者生产产品" + c + "通知消费者消费");
	}
	
	public synchronized char getData() {  //消费者消费产品
		if(!isProduced) {  //仓库中没有供消费的产品
			System.out.println("仓库中没有供消费的产品,消费者等待");
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		isProduced = false;   //标记为未生产
		notify();   //通知生产者生产
		System.out.println("消费者消费了" + this.c + "通知生产者继续生产");
		return c;
	}
}


2:生产者线程ProducerThread

package com.pb.consumerandproducer;

/**
 * 生产者线程,每隔一段时间就生产一个产品
 * @author ccna_zhang
 *
 */
public class ProducerThread extends Thread{
	
	private ShareData shareData;
	
	public ProducerThread(ShareData shareData) {
		this.shareData = shareData;
	}
	
	public void run() {
		for(char ch = 'A'; ch <= 'D'; ch++) {
			try {
				Thread.sleep((int)(Math.random()*3000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			shareData.putData(ch);   //把商品放进仓库
		}
	}
}


3:消费者线程ConsumerThread

package com.pb.consumerandproducer;

/**
 * 消费者线程
 * @author ccna_zhang
 *
 */
public class ConsumerThread extends Thread {

	private ShareData shareData;
	
	public ConsumerThread(ShareData shareData) {
		this.shareData = shareData;
	}
	
	public void run() {
		char ch;
		do {
			try {
				Thread.sleep((int)(Math.random()*3000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			ch = shareData.getData();  //从仓库中取出商品
			
		} while(ch != 'D');
	}
}


4:测试类和结果

package com.pb.consumerandproducer;

public class TestProcuderAndConsumer {

	public static void main(String[] args) {

		ShareData shareData = new ShareData();
		ConsumerThread consumerThread = new ConsumerThread(shareData);
		ProducerThread producerThread = new ProducerThread(shareData);
		
		consumerThread.start();
		producerThread.start();
		
	}
}


结果:

生产者生产产品A通知消费者消费
消费者消费了A通知生产者继续生产
仓库中没有供消费的产品,消费者等待
生产者生产产品B通知消费者消费
消费者消费了B通知生产者继续生产
仓库中没有供消费的产品,消费者等待
生产者生产产品C通知消费者消费
消费者消费了C通知生产者继续生产
生产者生产产品D通知消费者消费
消费者消费了D通知生产者继续生产


 

 

你可能感兴趣的:(java开发积累)