JUC篇
JUC是java.util.concurrent包的简称,在Java1.5添加,目的就是为了更好的支持高并发任务。让开发者进行多线程编程时减少竞争条件和死锁的问题。
1、虚假唤醒
1.1、导致原因
假设有线程A、B、C、D四个去操作一个资源number(number值为0),A、B线程执行加一操作,C、D线程执行减一操作。
public class Data {
// 表示数据个数
private int number = 0;
public synchronized void increment() throws InterruptedException {
if (number != 0) {
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName() + "生产了数据:" + number);
this.notify();
}
public synchronized void decrement() throws InterruptedException {
if (number == 0) {
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName() + "消费了数据:" + number);
this.notify();
}
}
public class Test {
public static void main(String[] args) {
Data data = new Data();
//生产者线程A
new Thread(() -> {
for (int i = 0;i < 5;i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
//生产者线程B
new Thread(() -> {
for (int i = 0;i < 5;i++) {
try {
data.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
//消费者线程C
new Thread(() -> {
for (int i = 0;i < 5;i++) {
try {
data.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
//消费者线程D
new Thread(() -> {