这是基于上一篇的笔记代码,JUC版Lock生产者和消费者问题
ReentrantLock:重入锁
Lock lock = new ReentrantLock(); //新建重入锁
Condition condition = lock.newCondition(); //Lock 替代了 synchronized 方法和语句的使用;Condition 替代了 Object 监视器方法的使用,也就是替代了notify()和wait(),名字变了一下换了唤醒和等待而已.
package com.xnizhi;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author LZP
* @create 2020/7/8
*/
@SuppressWarnings("all")
public class PC2 {
public static void main(String[] args) {
Data2 data = new Data2();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.add();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.del();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.del();
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
data.del();
}
}, "D").start();
}
}
class Data2 {
int number = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void add() {
lock.lock();
try {
while (number != 0) {
condition.await();//等待线程
}
number++;
System.out.println(Thread.currentThread().getName() + "是" + number);
condition.signalAll(); //唤醒全部线程
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public synchronized void del() {
lock.lock();
try {
while (number == 0) {
condition.await();//等待线程
}
number--;
System.out.println(Thread.currentThread().getName() + "是" + number);
condition.signalAll(); //唤醒全部线程
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}