import java.util.concurrent.atomic.AtomicInteger;
public class ew {
public ew(){
AtomicInteger a = new AtomicInteger();
AtomicInteger aq = new AtomicInteger();//临界区资源
final Object lock = new Object();
Thread A = new Thread(() -> {
while(true){
synchronized (lock){
if (aq.get() < 1 && a.get() < 3) {
aq.getAndIncrement();//0->1 区满
System.out.println("生产者开始运行");
System.out.println("生产者运行结束");
a.getAndIncrement();//0->1
System.out.println("生产者就绪");
aq.getAndDecrement();
lock.notify();
} else {
try {
System.out.println("--------生产者堵塞-------");
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
Thread B = new Thread(() -> {
while(true){
synchronized (lock){
if(aq.get() < 1 && a.get() > 0){
aq.getAndIncrement();
System.out.println("消费者开始运行");
System.out.println("消费者运行结束");
a.getAndDecrement();
System.out.println("消费者就绪");
aq.getAndDecrement();
lock.notify();
}else{
try {
System.out.println("*******消费者堵塞*********");
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
});
A.start();
B.start();
}
public static void main(String[] args) {
new ew();
}
}
zuizhongban
最新推荐文章于 2024-11-12 21:14:07 发布