黑马程序员_多线程:生产者消费者练习实例及问题

本文介绍了一个使用Java实现的生产者消费者模式案例。通过ReentrantLock和Condition实现了线程间的同步和等待通知机制,确保了资源的安全共享。多个生产者和消费者线程并发运行,展示了如何有效地控制产品的生产和消费。

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

今天把这个题目练习了一下,但是出现了一些问题,就是如何有效控制产品的产生数量,希望有人给讲解一下!

package com.itpractice;



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


public class ProducerAndConsumerDemo2 {


public static void main(String[] args) {


Resource2 res = new Resource2();


Thread t1 = new Thread(new Producer2(res));
Thread t2 = new Thread(new Producer2(res));
Thread t3 = new Thread(new Consumer2(res));
Thread t4 = new Thread(new Consumer2(res));


t1.start();
t2.start();
t3.start();
t4.start();
}


}


class Resource2 {
private String name;
private int count = 1;
private boolean flag = false;


private Lock lock = new ReentrantLock();


private Condition con_pro = lock.newCondition();
private Condition con_con = lock.newCondition();


public void setResource(String name) throws InterruptedException {


lock.lock();
try {
while (flag)
con_pro.await();
this.name = name + count++;


System.out.println(Thread.currentThread().getName() + "---生产者---"
+ this.name);
flag = true;
con_con.signal();
} finally {
lock.unlock();
}
}


public void outResource() throws InterruptedException {
lock.lock();
try {
while (!flag)
con_con.await();
System.out.println(Thread.currentThread().getName() + "---消费者---"
+ this.name);
flag = false;
con_pro.signal();
} finally {
lock.unlock();
}
}
}


class Producer2 implements Runnable {


private Resource2 res;


private int x = 0;


Producer2(Resource2 res) {
this.res = res;
}


public void run() {
while (x < 10) {
try {
res.setResource("产品");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


class Consumer2 implements Runnable {


private Resource2 res;


Consumer2(Resource2 res) {
this.res = res;
}


public void run() {
while (true) {
try {
res.outResource();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值