public class TestTV {
public static void main(String [] args){
TV tv=new TV();
new Thread(new jiemu(tv)).start();
new Thread(new guanzhong(tv)).start();
}
}
class jiemu implements Runnable{
TV tv;
public jiemu(TV tv) {<br /> this.tv = tv;<br /> }
@Override<br /> public void run() {<br /> for(int i=0;i<20;i++){<br /> if(i%2==0){<br /> tv.biaoyan("抖音记录美好生活");<br /> }else{<br /> tv.biaoyan("快乐大本营");<br /> }<br /> }<br /> }<br />}
class guanzhong implements Runnable{
TV tv;
public guanzhong(TV tv) {
this.tv = tv;
}
@Override<br /> public void run() {<br /> for(int i=0;i<20;i++){<br /> tv.shoukan();<br /> }<br /> }<br />}
class TV{
boolean flag=true; //是否在表演
String dsjm = “”;
public synchronized void biaoyan(String jm){<br /> if(flag){<br /> try {<br /> wait();<br /> } catch (InterruptedException e) {<br /> e.printStackTrace();<br /> }
}<br /> System._out_.println("电视在播放"+jm);<br /> dsjm=jm;<br /> this.notifyAll();<br /> this.flag=!this.flag;<br /> }
public synchronized void shoukan(){<br /> if (!flag){<br /> try {<br /> this.wait();<br /> } catch (InterruptedException e) {<br /> e.printStackTrace();<br /> }<br /> }<br /> System._out_.println("观众在收看"+dsjm);<br /> this.notifyAll();<br /> this.flag=!this.flag;<br /> }
}