package signallamp;
public class Test {
public static void main ( String[ ] args) {
Tv tv = new Tv ( ) ;
new Player ( tv) . start ( ) ;
new Watcher ( tv) . start ( ) ;
}
}
package signallamp;
public class Tv {
private String contant;
boolean flag = false ;
public synchronized void play ( String contant) {
if ( ! flag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "表演了 " + contant) ;
this . contant = contant;
this . notifyAll ( ) ;
this . flag = ! this . flag;
}
public synchronized void watch ( ) {
if ( flag) {
try {
this . wait ( ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
}
System. out. println ( "观看 " + contant) ;
this . notifyAll ( ) ;
this . flag = ! this . flag;
}
}
package signallamp;
public class Player extends Thread {
Tv tv;
public Player ( Tv tv) {
super ( ) ;
this . tv = tv;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
if ( i % 3 == 0 ) {
this . tv. play ( "小品" ) ;
} else if ( i % 3 == 1 ) {
this . tv. play ( "唱歌" ) ;
} else {
this . tv. play ( "爱情剧" ) ;
}
}
}
}
package signallamp;
public class Watcher extends Thread {
Tv tv;
public Watcher ( Tv tv) {
super ( ) ;
this . tv = tv;
}
@Override
public void run ( ) {
for ( int i = 0 ; i < 20 ; i++ ) {
this . tv. watch ( ) ;
}
}
}