消费者-生产者模式(线程的实现)

package dome3;

/**
 * 模式:生产者 -- 消费者模式
 * 引入模拟电影院情景(播放什么,观众看什么)
 * @author lzd
 *
 */

public class movies {
    private String pic;  //内容
    private boolean flag = true; //红绿灯模式,其标记作用

    /**
     * 
     * @param pic : 传入String 类型参数,表示传入的电影
     */
    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.pic = pic; 
        System.out.println("producer: " + pic);
        this.notify();
        flag = !flag;

    }

    public synchronized void watcher()
    {
        //等待播放
        if(flag)
        {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //直接播放
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("customer: "+ pic);
        this.notifyAll();
        flag = !flag;

    }


}
package dome3;

/**
 * 播放线程
 * @author lzd
 *
 */
public class Player implements Runnable{

    private movies movies1;
    public Player(movies movies1) {
        this.movies1 = movies1;
    }
    @Override
    public void run() {
        for(int i = 1; i <= 20; i++)
            if(i%2==0)
                movies1.play("左青龙");
            else {
                movies1.play("右白虎");
            }

    }

}
package dome3;

/**
 * 观看线程
 * @author lzd
 *
 */

public class Watcher implements Runnable{
    private movies movies1;

    public Watcher(movies movies1) {
        this.movies1 = movies1;
    }


    @Override
    public void run() {
        for(int i = 1; i <= 20 ; i++)
            movies1.watcher();          
    }

}
package dome3;

/**
 * 主函数
 * @author lzd
 *
 */

public class App {

    public static void main(String[] args) {
        movies m = new movies();
        Player p = new Player(m);
        Watcher w = new Watcher(m);
        Thread producer = new Thread(p);
        Thread customer = new Thread(w);

        producer.start();
        customer.start();


    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值