154.信号灯法

    科技2022-07-29  113

    管程法的特点是,生产者和消费者之间是借助标志位达到线程同步的

    写一个影院电影上线和观众等待电源上线的多线程例子
    /* * 协作模式:生产者消费者实现方式2:信号灯法 */ public class coTest02 { public static void main(String[] args) { danceHall dh = new danceHall(); new player(dh).start(); new auidence(dh).start(); } } //生产者 演员 class player extends Thread{ danceHall ah; public player(danceHall ah) { super(); this.ah = ah; } public void run() { String[] str = new String[3]; str[0] = "奇葩说"; str[1] = "一人之下"; str[2] = "权力的游戏"; for(String st : str) { ah.play(st); } } } //消费者 观众 class auidence extends Thread{ danceHall ah; public auidence(danceHall ah) { super(); this.ah = ah; } public void run() { for(int i=0; i<3; ++i) ah.view(); } } //同一个资源:影院 class danceHall{ private String item; /* * 信号灯 * T 演员表演,观众等待 * F 观众观看,演员等待 */ boolean flag = true; //表演 public synchronized void play(String it) { //F if(!flag) { try { this.wait(); } catch (InterruptedException e) { } } //T System.out.println("表演了"+it); this.item = it; this.notify(); this.flag = !this.flag; } //观看 public synchronized void view() { //T if(flag) { try { this.wait(); } catch (InterruptedException e) { } } //F System.out.println("观看了"+this.item); this.notify(); this.flag = !this.flag; } }

    通过标志位,达到线程之间对资源请求操作的阻塞和唤醒切换,主要注意的地方就是当前线程操作完成后除了要唤醒其它线程之外还有更改标志位

    Processed: 0.023, SQL: 8