package com. liu. gaoji;
public class TestPC2 {
public static void main ( String[ ] args) {
TV tv = new TV ( ) ;
TVStation tvStation = new TVStation ( tv) ;
Audience audience = new Audience ( tv) ;
tvStation. start ( ) ;
audience. start ( ) ;
}
}
class TVStation extends Thread {
TV tv;
public TVStation ( TV tv) {
this . tv = tv;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 10 ; i++ ) {
if ( i% 3 == 0 ) {
try {
this . tv. play ( "西虹市首富" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
} else if ( i% 3 == 1 ) {
try {
this . tv. play ( "大江大河" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
} else {
try {
this . tv. play ( "家有儿女" ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
}
}
class Audience extends Thread {
TV tv;
public Audience ( TV tv) {
this . tv = tv;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 10 ; i++ ) {
try {
tv. watch ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
}
}
class TV {
String program;
boolean flag = true ;
public synchronized void play ( String program) throws InterruptedException {
if ( ! flag) {
this . wait ( ) ;
}
System. out. println ( "电视台准备了节目:" + program) ;
this . notifyAll ( ) ;
this . program = program;
this . flag = ! this . flag;
}
public synchronized void watch ( ) throws InterruptedException {
if ( flag) {
this . wait ( ) ;
}
System. out. println ( "观众观看了节目:" + program) ;
System. out. println ( ) ;
this . notifyAll ( ) ;
this . flag = ! this . flag;
}
}