08-Lock版的生产者消费者问题
JUC版的生产者和消费者问题
其中的await() 方法属于 condition
通过Lock可以找到Condition
代码实现:
package com.hkx.pc;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @program: juc
* @description: JUC版的生产者和消费者问题
* @author: Casey Hu
* @create: 2022-08-07 21:41
**/
public class B {
public static void main(String[] args) {
Data2 data = new Data2();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.increment();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"A").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"B").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.increment();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"C").start();
new Thread(()->{
for (int i=0;i<10;i++){
try {
data.decrement();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"D").start();
}
}
class Data2{
private int number=0;
Lock lock=new ReentrantLock();
Condition condition = lock.newCondition();
// condition.await(); //等待
// condition.signalAll(); //唤醒全部
//加一操作
public void increment() throws InterruptedException {
try {
lock.lock();
//业务代码
while (number!=0){
condition.await(); //等待操作
}
number++;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,完成了加一操作
condition.signalAll();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
//减一操作
public void decrement() throws InterruptedException {
try {
lock.lock();
while (number==0){
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+"=>"+number);
//通知其他线程,完成了减一操作
condition.signalAll();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}
任何新技术的创新,绝对不是仅仅只是覆盖了原来的技术,优势和补充
Condition 精准的通知和唤醒线程
接下来,要进行有序执行A B C D 的唤醒