public class TestArraylist {
public static void main(String[] args) {
AirCondition airCondition = new AirCondition();
new Thread(()->{
for (int i = 1; i <11 ; i++) {
try {
Thread.sleep(100);
airCondition.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 1; i <11 ; i++) {
try {
Thread.sleep(200);
airCondition.relese();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"B").start();
new Thread(()->{
for (int i = 1; i <11 ; i++) {
try {
Thread.sleep(300);
airCondition.add();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"C").start();
new Thread(()->{
for (int i = 1; i <11 ; i++) {
try {
Thread.sleep(400);
airCondition.relese();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"D").start();
}
}
/*
线程操作资源库
*/
/**
* @auther zzyy
* @create 2020-03-26 11:41
*
* 有一个初始值为零的变量,现有两个线程对该变量操作,
* 实现一个线程对变量加1,实现一个线程对变量减1,交替来10轮
*
* 1 高内聚低耦合的前提下,线程 操作 资源类
* 2 判断、干活和通知
* 3 防止多线程的【虚假唤醒】,wait被唤醒了,需要重新进行一次判断,记得用while
*/
class AirCondition{
int number=0;
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
public void add() throws InterruptedException {
lock.lock();
try {
//判断
while (number!=0){
condition.await();
}
//干活
System.out.println(Thread.currentThread().getName()+(++number));
//通知
condition.signalAll();
}finally {
lock.unlock();
}
}
public void relese() throws InterruptedException {
lock.lock();
try {
//判断
while (number==0){
condition.await();
}
//干活
System.out.println(Thread.currentThread().getName()+(--number));
//通知
condition.signalAll();
}finally {
lock.unlock();
}
}
// public synchronized void add() throws InterruptedException {
// //1.判断
// while (number!=0){
// this.wait();
// }
// //2.干活
// System.out.println(Thread.currentThread().getName()+(++number));
// //3.通知
// this.notifyAll();
// }
// public synchronized void relese() throws InterruptedException {
// //1.判断
// while (number==0){
// this.wait();
// }
// //2.干活
// System.out.println(Thread.currentThread().getName()+(--number));
// //3.通知
// this.notifyAll();
// }
}
生产者消费者的问题
最新推荐文章于 2023-04-26 09:27:27 发布