多线程:信号灯法
package com.wuming.thread;//測試生產(chǎn)者消費(fèi)者問題2:信號燈法,標(biāo)志位解決
public class TestPc2 {public static void main(String[] args) {TV tv = new TV();new Player(tv).start();new Watcher(tv).start();}
}
//生產(chǎn)者-->演員
class Player extends Thread{TV tv;/*** Allocates a new {@code Thread} object. This constructor has the same* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}* {@code (null, null, gname)}, where {@code gname} is a newly generated* name. Automatically generated names are of the form* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.*/public Player(TV tv) {this.tv = tv;}@Overridepublic void run() {for (int i = 0; i < 20; i++) {if (i%2==0){this.tv.play("快樂大本營播放中");}else{this.tv.play("抖音:記錄美好生活");}}}
}
//消費(fèi)者-->觀眾
class Watcher extends Thread{TV tv;/*** Allocates a new {@code Thread} object. This constructor has the same* effect as {@linkplain #Thread(ThreadGroup, Runnable, String) Thread}* {@code (null, null, gname)}, where {@code gname} is a newly generated* name. Automatically generated names are of the form* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.*/public Watcher(TV tv) {this.tv=tv;}@Overridepublic void run() {for (int i = 0; i < 20; i++) {tv.watch();}}
}
//產(chǎn)品-->節(jié)目
class TV{//演員表演,觀眾等待//觀眾觀看,演員等待String voice;//表演的節(jié)目boolean flag=true;//表演public synchronized void play(String voice){if (!flag){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("演員表演了"+voice);//通知觀眾觀看this.notifyAll();//通知喚醒this.voice=voice;this.flag=!this.flag;}//觀看public synchronized void watch(){if (flag){try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("觀看了:"+voice);//通知演員表演this.notifyAll();this.flag=!flag;}
}
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
演員表演了快樂大本營播放中
觀看了:快樂大本營播放中
演員表演了抖音:記錄美好生活
觀看了:抖音:記錄美好生活
總結(jié)
- 上一篇: jq之animate() toggle
- 下一篇: BugkuCTF-MISC题啊哒,白哥的