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("生产者生产");
a.getAndIncrement();//0->1
System.out.println("ok");
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("消费者消费");
a.getAndDecrement();
System.out.println("ok");
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();
}
}
wekeshagiede
最新推荐文章于 2024-11-12 21:14:07 发布