生产者、消费者、java 、线程

    xiaoxiao2023-11-25  173

    资源: 

    package chap9; /** * 一个场景 电影是共同的资源 * 信号灯法 * * * @author wwq * */ public class Movie { private String pic; //信号灯 private boolean flag=true; //flag-->T 生产者生产,消费者等待,生产完成后通知消费 //flag-->F 生产者等待,消费者消费,消费完成后通知生产 /** * 播放的功能 * @param */ public synchronized void play(String pic) { if (!flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //开始生产 try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.pic=pic; this.notify(); this.flag=false; } /** * 观看的功能 * @param * */ public synchronized void watch() { if (flag) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //开始消费 try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(pic); this.notify(); this.flag=true; } }

    生产者:

    package chap9; /**  * 生产者  *   * @author wwq  *  */ public class Player implements Runnable{     private Movie m;     public Player(Movie m) {         super();         this.m = m;     }               @Override     public void run() {         // TODO Auto-generated method stub         for (int i = 0; i < 20; i++) {             if (0==i%2) {                 m.play("左青龙");             }else {                 m.play("右白虎");             }         }     }           }

    消费者:

    package chap9; /** * 观看者 * @author wwq * */ public class Watcher implements Runnable { private Movie m; public Watcher(Movie m) { super(); this.m = m; } @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i <20; i++) { m.watch(); } } }

    主程序start

    package chap9; public class App { public static void main(String[] args) { //共同的资源 Movie m=new Movie(); Player p=new Player(m); Watcher w=new Watcher(m); new Thread(p).start(); new Thread(w).start(); } }

     

    最新回复(0)