package time_3_22;
/*
生产者消费者问题
生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,店员一次只能持有固定数量的产品(比如20个)
分析:
贡献数据:产品
多线程问题:生产者,消费者
*/
class Clerk{
private int num = 0;
//生产产品
public synchronized void produceProductor(){
if(num < 20){
num++;
System.out.println(Thread.currentThread().getName() + ":开始生产第" + num + "产品");
notify(); //唤醒消费者消费
}else{
try {
wait(); //释放锁,不能单独使用wait(),需要在try-catch中使用
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费产品
public synchronized void produceCustomer(){
if(num > 0){
System.out.println(Thread.currentThread().getName() + ":开始消费第" + num + "产品");
num--;
notify(); //唤醒生产者生产
}else{
try {
wait(); //释放锁
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//生产者
class Productor extends Thread{
private Clerk clerk;
public Productor(Clerk clerk) { //构造器,创建类时需要传入参数
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ";开始生产" );
while(true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceProductor(); //调用生产方法
}
}
}
//消费者
class Customer_2 extends Thread{
private Clerk clerk;
public Customer_2(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ";开始消费");
while(true){
try { //线程休眠
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produceCustomer();
}
}
}
public class ProductTest {
public static void main(String[] args) {
Clerk clerk = new Clerk(); //同一个锁
Productor p1 = new Productor(clerk);
Customer_2 c2 = new Customer_2(clerk);
p1.setName("生产者");
c2.setName("消费者");
p1.start();
c2.start();
}
}
生产者-消费者问题:Java
最新推荐文章于 2024-04-15 08:10:08 发布