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();
}
}
本文通过一个具体的Java程序示例介绍了线程间的同步机制,包括如何使用wait和notifyAll方法来实现生产者与消费者模式。两个线程分别扮演播放者和观看者的角色,交替进行操作,展示了线程间如何通过synchronized关键字和对象锁来协调运行。
278

被折叠的 条评论
为什么被折叠?



