使用Condition重写waitnotify生产者消费者模型案例
作者:互联网
//天猫商品
package com.roocon.thread.ta7;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Tmall2 {
private int count;
private Lock lock = new ReentrantLock();
Condition p = lock.newCondition();
Condition t = lock.newCondition();
public final int MAX_COUNT = 10;
public void push() {
lock.lock();
while (count >= MAX_COUNT) {
try {
System.out.println(Thread.currentThread().getName() + " 库存数量达到上限,生产者停止生产。");
p.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count++;
System.out.println(Thread.currentThread().getName() + " 生产者生产,当前库存为:" + count);
t.signal();
lock.unlock();
}
public void take() {
lock.lock();
while (count <= 0) {
try {
System.out.println(Thread.currentThread().getName() + " 库存数量为零,消费者等待。");
t.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
System.out.println(Thread.currentThread().getName() + " 消费者消费,当前库存为:" + count);
p.signal();
lock.unlock();
}
}
//生产者
package com.roocon.thread.ta7;
public class PushTarget implements Runnable {
private Tmall tmall;
public PushTarget(Tmall tmall) {
this.tmall = tmall;
}
@Override
public void run() {
while(true) {
tmall.push();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
package com.roocon.thread.ta7;
public class TakeTarget implements Runnable {
private Tmall tmall;
public TakeTarget(Tmall tmall) {
this.tmall = tmall;
}
@Override
public void run() {
while(true) {
tmall.take();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//main
package com.roocon.thread.ta7;
public class Main {
public static void main(String[] args) {
Tmall tmall = new Tmall();
PushTarget p = new PushTarget(tmall);
TakeTarget t = new TakeTarget(tmall);
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(p).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
标签:Thread,tmall,lock,start,waitnotify,new,重写,public,Condition 来源: https://blog.csdn.net/cckkpp/article/details/88598056