17、管程
- 总览
17.1、为什么要引入管程?
17.2、管程的定义和基本特征
17.3、管程实现生产者消费者
17.4、Java中类似管程机制
public class NotifyWaitDemoReview {
public static void main(String[] args) {
//线程操纵资源类
ShareData shareData = new ShareData();
//生产者
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareData.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
//消费者
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
shareData.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
}
}
class ShareData {
private int number = 0;
public synchronized void increment() throws InterruptedException {
//1.判断
while (number != 0) {
this.wait();
}
//2.干活
++number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3.通知
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
//1.判断
while (number == 0) {
this.wait();
}
//2.干活
--number;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3.通知
this.notifyAll();
}
}