标签:new code 信号 rac run cat tar watcher tpc
//信号灯法 标志位
public class TestPC2 {
public static void main(String[] args) {
Program program = new Program();
new Player(program).start();
new Watcher(program).start();
}
}
//表演者
class Player extends Thread{
Program program;
public Player(Program program) {
this.program = program;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (i%2 == 0){
program.player("java");
}else {
program.player("mysql");
}
}
}
}
//观看者
class Watcher extends Thread{
Program program;
public Watcher(Program program) {
this.program = program;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
program.watcher();
}
}
}
//节目
class Program{
//节目的名字
String name;
//标志位 默认没有节目
boolean flag = true;
//表演
public synchronized void player(String name){
//如果有节目 等待
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:" + name);
this.name = name;
//更改标志位
flag = !flag;
//让观众观看
this.notifyAll();
}
//观看
public synchronized void watcher(){
//如果没有节目 等待
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了回放: " + name );
//更改标志位
flag = !flag;
//唤醒表演者
this.notifyAll();
}
}
标签:new code 信号 rac run cat tar watcher tpc
原文地址:https://www.cnblogs.com/immortal-mode/p/14394379.html