Java 多线程生产者和消费者代码示例


共享资源代码:

package com.hycz.producer.consumer;

public class Box {
	
	private int data;
	private boolean variable = false; //同步标识符
	
	public synchronized void put(int data){
		while(variable){//当同步标识符为true时,所有生产者线程调用的put()方法时都从运行状态变成阻塞状态,不进行生产。
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		variable = true; // 改变标识符
		this.data = data;
		notifyAll(); // 唤醒所以处于阻塞状态的消费者线程,提醒它们现在产品可以进行消费。
	}
	
	public synchronized int get(){
		while(!variable){ // 当同步标识符为false时,所有消费者线程调用get()方法时都从运行状态变成阻塞状态,不进行消费。
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		variable = false; // 改变标识符
		notifyAll(); // 唤醒所以处于阻塞状态的生产者线程,提醒它们进行产口的生产。
		return this.data;
	}

}


生产者代码:

package com.hycz.producer.consumer;

public class Producer extends Thread {
	
	private Box box;
	
	public Producer(Box box) {
		super();
		this.box = box;
	}

	@Override
	public void run() {
		for(int i = 0; i<10; i++){
			box.put(i);
			System.out.println("Producer put = " + i);
			try {
				Thread.sleep((int)Math.random()*100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	

}


消费者代码:

package com.hycz.producer.consumer;

public class Consumer extends Thread {
	
	private Box box;

	public Consumer(Box box) {
		this.box = box;
	}

	@Override
	public void run() {
		int value = 0;
		for(int i=0; i<10; i++){
			value = box.get();
			System.out.println("Consumer get = " + value);
		}
	}
	
	
	

}

测试代码:

package com.hycz.producer.consumer;

public class ProducerConsumerTest {
	
	public static void main(String[] args) {
		Box box = new Box();
		Thread producer = new Producer(box);
		Thread consumer = new Consumer(box);
		producer.start();
		consumer.start();
	}

}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值