import java.util.concurrent.atomic.AtomicInteger;
public class Test {
public Test() {
final Object lock = new Object();
AtomicInteger a = new AtomicInteger();
AtomicInteger aq = new AtomicInteger(5);
Thread A = new Thread(() -> {
int ci = 210;
while (ci > 0) {
synchronized (lock) {
if(a.get() < aq.get()){
a.getAndIncrement();
System.out.println("生产者执行");
lock.notify();
}else {
try {
System.out.println("*********************生产者堵塞********************");
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
ci--;
}
});
Thread B = new Thread(() -> {
while (true) {
synchronized (lock) {
a.getAndDecrement();
if (a.get() >= 0) {
System.out.println("消费者执行");
lock.notify();
} else {
System.out.println("-------------------消费者堵塞------------------------");
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
A.start();
B.start();
}
public static void main(String[] args) {
new Test();
}
}
以PV原语为基础实现生产者消费者问题
最新推荐文章于 2024-07-30 20:50:32 发布