并发之涂蜡-抛光问题。

经过周末两天煎熬,《编程思想》的并发章节,看完了三分之一,看的确实很费劲,莫办法,第一次看总是痛苦的,以我的经验来说,我学任何新知识,第一遍都会很困难。以后再复习就会好很多,好在我有画思维导图,以后看导图回忆,哪块忘了,很快定位。

这个汽车涂蜡抛光问题,主要加深wait(),notify(),notifyAll()三个方法理解,需要注意的是这三个并发方法是Object的方法,使用的前提是必须已经持有锁对象。和sleep()等方法不一样。

wait():使线程进入阻塞状态,并且失去锁,只能由其他线程唤醒

notify():唤醒等待当前线程的锁的阻塞线程中的某一个线程,具体是某一个线程,由线程调度器决定。突然感觉和yield()方法相似。

notifyAll():唤醒等待当前线程的锁的阻塞线程中的所有线程。              唤醒了沉睡中的木乃伊大军。

package com.houjun.current;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: HouJun
 * @Date: 2019/10/14 8:42
 * @Description: 汽车上蜡与抛光轮替线程问题
 * @version: 1.0
 */
class Car {
    private boolean waxOn = false;//表示涂蜡-抛光的状态 waxOn=true正在涂蜡,

    public synchronized void waxed() {//已上蜡
        waxOn = true;//设置true代表已经上蜡了
        notifyAll();//唤醒等待的所有线程
    }

    public synchronized void buffed() {//已抛光
        waxOn = false;//设置false代表已经抛光了
        notifyAll();//唤醒等待的所有线程
    }


    public synchronized void waitForWaxing() throws InterruptedException {
        while (waxOn == false) {//判断是否已经抛光,是就等待,第一次进来是false
            wait();
        }
    }

    public synchronized void waitForBuffering() throws InterruptedException {
        while (waxOn == true) {//判断是否已经涂蜡,是就等待
            wait();
        }
    }

}

//上蜡
class WaxOn implements Runnable {
    private Car car;

    public WaxOn(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                System.out.println("Wax on! ");//开始上蜡
                TimeUnit.MILLISECONDS.sleep(200);//模拟上蜡过程
                car.waxed();//设置状态为已上蜡
                car.waitForBuffering();//循环判断 是否已经抛光 是就循环,否就wait等待别人唤醒
            }
        } catch (InterruptedException e) {
            System.out.println("Exiting via interrupt");
        }
        System.out.println("Ending Wax On task");//结束上蜡工作
    }
}

//抛光
class WaxOff implements Runnable {
    private Car car;

    public WaxOff(Car car) {
        this.car = car;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                car.waitForWaxing();//判断是否已经抛光过,是就wait等别人唤醒
                System.out.println("Wax off!");//抛光开始
                TimeUnit.MILLISECONDS.sleep(200);
                car.buffed();//抛光结束,更改car的waxOn状态为false
            }
        } catch (InterruptedException e) {
            System.out.println("Exiting via interrupt");//抛光任务被打断
        }
        System.out.println("Ending Wax off task");//结束抛光工作
    }
}

public class WaxOMatic {
    public static void main(String[] args) throws InterruptedException {
        Car car = new Car();
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(new WaxOff(car));
        service.execute(new WaxOn(car));
        TimeUnit.SECONDS.sleep(5);
        service.shutdownNow();
    }
}
原文地址:https://www.cnblogs.com/houj/p/11670398.html