Java 多线程 防止死锁 生产者与消费者模式 信号灯法

/**
 * 一个场景,共同的资源 
 * 生产者与消费者模式 信号灯法
 * 解决多线程防止死锁的方法
 */

public class ProducerAndConsumerModels {
    public static void main(String[]args){
        //共同的资源
        Movie movie = new Movie();

        //多线程
        Player player = new Player(movie);
        Watcher watcher = new Watcher(movie);

        new Thread(player).start();
        new Thread(watcher).start();
    }
}
/**
 * 一个场景,共同的资源
 * 生产者与消费者模式 信号灯法
 * wait():等待,释放锁    sleep():不释放锁
 * notify() / motyfyAll():唤醒
 * @author 彼岸夜微凉
 */
public class Movie {
    private String m_pic;

    //信号灯
    //flag --> T 生产者生产,消费者等待,生产完后通知消费
    //flag --> F 消费者消费,生产者等待,消费完后通知生产
    private boolean flag = true;

    public synchronized void play(String pic){
        if(!flag){ // 生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //开始生产
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //生产完毕
        this.m_pic = pic;
        //通知消费
        this.notify();
        //生产者停下
        this.flag = false;
    }

    public synchronized void watch(){
        if(flag){ // 消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //开始消费
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(m_pic);
        //通知生产
        this.notify();
        //消费停止
        this.flag = true;
    }
}
/**
 * 生产者
 */
public class Player implements Runnable {
    private Movie m_movie;

    public Player(Movie movie){
        m_movie = movie;
    }

    @Override
    public void run() {
        for(int i=0;i <20; i ++){
            if(i % 2 == 0){
                m_movie.play("左青龙");
            }else {
                m_movie.play("右白虎");
            }
        }
    }
}
/**
 * 消费者
 */
public class Watcher implements Runnable {
    private Movie m_movie;

    public Watcher(Movie movie){
        m_movie = movie;
    }

    @Override
    public void run() {
        for(int i = 0;i < 20;i ++){
                m_movie.watch();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40990854/article/details/81217025