import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 线程操作资源类
* 判断、干活、通知
* 防止虚假唤醒通知
*/
class ShareData {
private int number;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void increment() throws Exception {
// 获取锁
lock.lock();
try {
// 1.判断(这里要用while 防止虚假唤醒)
while (number != 0) {
// 等待,不能生产
condition.await();
}
// 2.干活
number++;
System.out.println(Thread.currentThread().getName() + "\t" + number);
// 3.通知唤醒
condition.signalAll();
}finally {
// 释放锁
lock.unlock();
}
}
public void decrement() throws Exception {
// 获取锁
lock.lock();
try {
// 1.判断
while (number == 0) {
// 等待,不能生产
condition.await();
}
// 2.干活
number--;
System.out.println(Thread.currentThread().getName() + "\t" + number);
// 3.通知唤醒
condition.signalAll();
}finally {
// 释放锁
lock.unlock();
}
}
}
/**
* 一个初始值为0的变量,多个线程对其交替操作,一个加一个减,循环5次
*/
public class ProducerConsumerDemo01 {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(()-> {
for(int i = 0; i < 5; i++) {
try {
shareData.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "AA").start();
new Thread(()-> {
for(int i = 0; i < 5; i++) {
try {
shareData.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "BB").start();
new Thread(()-> {
for(int i = 0; i < 5; i++) {
try {
shareData.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "CC").start();
new Thread(()-> {
for(int i = 0; i < 5; i++) {
try {
shareData.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "DD").start();
}
}
生产者消费者模式
最新推荐文章于 2021-08-06 01:49:42 发布