package com.itjava.interview;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareData { //资源类
private int number = 0;
private Lock lock = new ReentrantLock(); //lock
private Condition condition = lock.newCondition(); //调用其中的方法用来睡眠或者唤醒线程
public void increment() throws Exception {
lock.lock();
try {
//1 判断
while (number != 0) {
//等待,不能生产
condition.await();
}
//2 干活
number++;
System.out.println(Thread.currentThread().getName() + "\t" + number);
//3 通知唤醒
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} 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();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
/**
* 题目:一个初始值为零的变量,两个线程对其交换对其交操作,一个加1一个减1,来5轮
* <p>
* 高内聚,低耦合的前提下。 线程操作资源类 。判断,干活,唤醒通知 。 严防多线程下的虚假唤醒!
* 1 线程 操作(方法) 资源类
* 2 判断 干活 通知
* 3 防止虚假唤醒机制(用while做判断!)
*/
public class ProdConsumer_TraditionDemo {
public static void main(String[] args) {
ShareData shareData = new ShareData();
new Thread(()->{
for (int i = 1; i <=5; i++) {
try {
shareData.increment();
} catch (Exception e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(()->{
for (int i = 1; i <=5; i++) {
try {
shareData.decrement();
} catch (Exception e) {
e.printStackTrace();
}
}
},"BB").start();
}
}