Java 生产者消费者实现方式

本文通过三种不同的方式实现了生产者消费者模式:一是利用同步队列LinkedBlockingQueue;二是使用Lock和Condition;三是采用synchronized关键字。每种实现都详细展示了如何在多线程环境下进行资源的生产和消费。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1,使用 [color=red]同步队列[/color] 解决任务协调
2,使用 常规[color=red]Lock,Condition[/color]解析任务协调
3,使用[color=red]synchronized[/color]加锁机制

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class ProducerAndConsumer {
public static void main(String[] args) throws Exception {
CoinBox box = new CoinBox();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Consumer(box));
exec.execute(new Producer(box));

TimeUnit.MILLISECONDS.sleep(1);
exec.shutdownNow();
}
}

class Coin {
private final int id;

public Coin(int idn) {
id = idn;
}
@Override
public String toString() {
return "Coin [id=" + id + "]";
}

}

class CoinBox {
LinkedBlockingQueue<Coin> box = new LinkedBlockingQueue<Coin>();

public void producess(Coin coin){
box.add(coin);
System.out.println("投入硬币:" + coin);
}
public void consumer(){
try {
// Coin coin = box.take();
Coin coin = box.poll();
if(coin == null){
System.err.println("拿走硬币:" + coin);
}else{
System.out.println("拿走硬币:" + coin);
}
} catch (Exception e) {
System.err.println("consumer exception");
}
}

}

class Consumer implements Runnable {
private CoinBox box;

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

@Override
public void run() {
while(!Thread.interrupted()){
box.consumer();
}
}
}

class Producer implements Runnable {
private CoinBox box;
private Random rand = new Random(47);

public Producer(CoinBox box) {
this.box = box;
}

@Override
public void run() {
while(!Thread.interrupted()){
Coin coin = new Coin(rand.nextInt(500));
box.producess(coin);
}
}
}



import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerImpl {
public static void main(String[] args) {
Store store = new Store();

ExecutorService proConServiceExecutor = Executors.newFixedThreadPool(2);
Producer1 producer = new Producer1(store);
Consumer1 consumer = new Consumer1(store);

try {
proConServiceExecutor.execute(producer);
proConServiceExecutor.execute(consumer);
} catch (Exception e) {
e.printStackTrace();
} finally {
proConServiceExecutor.shutdown();
}
}
}

class Store {

private Lock producerConsumberLock;
private Condition producerCondition;
private Condition consumerCondition;

private final int POOL_SIZE = 2;
private int productNumber;
private int[] productPool;

public Store() {
productPool = new int[POOL_SIZE];
productNumber = 0;

producerConsumberLock = new ReentrantLock();
producerCondition = producerConsumberLock.newCondition();
consumerCondition = producerConsumberLock.newCondition();
}

public void produce() {
try {
while (productNumber >= POOL_SIZE) {
System.out.println("productNumber=" + productNumber);
System.out.println("Pool is full, producer " + Thread.currentThread().getName() + " wait...");
producerCondition.await();
}

producerConsumberLock.lock();
productPool[productNumber++] = 1;
System.out.println(Thread.currentThread().getName() + " Porduced a product....");

if (productNumber > 0) {
consumerCondition.signalAll();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
producerConsumberLock.unlock();
}

}

public void consume() {
try {
while (productNumber <= 0) {
System.out.println("productNumber=" + productNumber);
System.out.println("Pool is empty, consumer " + Thread.currentThread().getName() + " wait...");
consumerCondition.await();
}

producerConsumberLock.lock();
productNumber--;
System.out.println(Thread.currentThread().getName() + " Consumed a product....");
if (productNumber <= POOL_SIZE - 1 && productNumber >= 0) {
producerCondition.signalAll();
}

} catch (Exception e) {
e.printStackTrace();
} finally {
producerConsumberLock.unlock();
}

}

}

class Consumer1 implements Runnable {
private Store pcl;

public Consumer1(Store pcl) {
this.pcl = pcl;
}

@Override
public void run() {
while (true) {
pcl.consume();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}

class Producer1 implements Runnable {
private Store pcl;

public Producer1(Store pcl) {
this.pcl = pcl;
}
@Override
public void run() {
while (true) {
pcl.produce();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

}



public class PiggyMoney {
public static void main(String[] args) throws InterruptedException {
Bank bank = new Bank();
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new CoinIn(bank));
exec.execute(new CoinOut(bank));

TimeUnit.MILLISECONDS.sleep(3);
List results = exec.shutdownNow();
for (Object object : results) {
System.out.println(object);
}
}
}

class Bank {
private List<Money> bank = new LinkedList<Money>();

public synchronized void coinIn() {
try {
Money money = new Money();
bank.add(money);
System.out.println("主淫存入" + money);

if (bank.size() > 0) {
notifyAll();
}
} catch (Exception e) {
e.printStackTrace();
}
}

public synchronized void coinOut() {
try {
if (bank.size() <= 0) {
System.err.println("主淫,您不能透支啊....");
wait();
}

Money money = bank.get(0);
bank.remove(money);
System.out.println("主淫取出" + money);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

class CoinOut implements Runnable {
private Bank bank;

public CoinOut(Bank bank) {
this.bank = bank;
}

@Override
public void run() {
while (!Thread.interrupted()) {
bank.coinOut();
}
}
}

class CoinIn implements Runnable {
private Bank bank;

public CoinIn(Bank bank) {
this.bank = bank;
}

@Override
public void run() {
while (!Thread.interrupted()) {
bank.coinIn();
}
}
}

class Money {
private int id = counter++;
private static int counter = 1;

@Override
public String toString() {
return "Money [id=" + id + "]";
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值