package com.company;
/**
* 消费者和生产者:线程之间的通信问题
* 等待唤醒,通知唤醒
* 不同的线程操作同一个变量
*/
public class ProducerAndConsumer {
public static void main(String[] args) {
Data data = new Data();
//添加线程
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"添加线程").start();
//减少线程
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"减少线程").start();
}
}
//资源类
class Data{
//不同的线程操作number
private int number = 0;
//number++
public synchronized void increment() throws InterruptedException {
while (number != 0){
//等待number--
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知number--的线程,我number++完毕了
this.notify();
}
//number--
public synchronized void decrement() throws InterruptedException {
while (number == 0){
//等待number++
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知number++线程,我number--完毕了
this.notify();
}
}
运行结果如下: