package sai.company.lesson3;
public class TestPC2 {
public static void main(String[] args) {
TV tv=new TV();
new Player(tv).start();
new Wacther(tv).start();
}
}
class Player extends Thread{
TV tv ;
public Player(TV tv) {
this.tv = tv;
}
public void run() {
for (int i = 1; i <20 ; i++) {
try {
tv.play("相棒"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Wacther extends Thread{
TV tv ;
public Wacther(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i <20 ; i++) {
try {
Thread.sleep(2000);
tv.wacth();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class TV {
String games;
boolean flag=true;
public synchronized void play(String games) throws InterruptedException {
if(!flag){
this.wait();
}
System.out.println("刘德华演了"+games);
this.games=games;
this.flag=!this.flag;//取反,这个很重要
this.notifyAll();
}
public synchronized void wacth() throws InterruptedException {
if(flag){
this.wait();
}
System.out.println("白嫖观众看了"+games);
this.flag=!this.flag;
this.notifyAll();
}
}