Java模拟生产消费问题

生产者代码

package com.cvicse.thread.product_consumer;

public class Producter extends Thread{

	private ShareData shareData;
	
	public Producter(ShareData shareData){
		this.shareData = shareData;
	}
	
	@Override
	public void run() {
		for (char c = 'A'; c <= 'D'; c++) {
			try {
				Thread.sleep((long)(Math.random()*1000));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			shareData.putShareChar(c);
			System.out.println(c + " is produced by Producer. ");
		}
	}
}

消费者代码

package com.cvicse.thread.product_consumer;

public class Consumer extends Thread{

	private ShareData shareData;
	
	public Consumer(ShareData shareData){
		this.shareData = shareData;
	}
	
	@Override
	public void run() {
		char ch;
		do{
			try{
				Thread.sleep((long)(Math.random()*1000));
			}catch(InterruptedException e){
				e.printStackTrace();
			}
			// 从仓库中取出产品
			ch = shareData.getShareChar(); 
			System.out.println(ch + " is consumed by Consumer. ");
		}while (ch != 'D');
	}
}

仓库代码

package com.cvicse.thread.product_consumer;

public class ShareData {
	
	private char c;
	private boolean signal = false;
	
	public synchronized void putShareChar(char c){
		while (signal) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.c = c;
		this.signal = true;
		notify();
	}
	
	public synchronized char getShareChar(){
		while (!signal) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		this.signal = false;
		notify();
		return this.c;
	}
}

测试类

package com.cvicse.thread.product_consumer;

public class MainTest {

	public static void main(String[] args) {
		ShareData shareData = new ShareData();
		
		Thread producter = new Producter(shareData);
		Thread consumer = new Consumer(shareData);
		
		producter.start();
		consumer.start();
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值