Film.java
package FilmTest;
public class Film {
private String name;
private boolean flag = true;
public synchronized void play(String name) {
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("producer-1"+name);
this.name = name;
// System.out.println(name);
this.notify();
this.flag = false;
}
Player.java
package FilmTest;
public class Player implements Runnable {
private Film film;
public Player(Film film) {
// TODO Auto-generated constructor stub
this.film = film;
}
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
if(0==i%2){
film.play("film-1-"+i);
}else{
film.play("film-2-"+i);
}
}
}
}
Watcher.java
package FilmTest;
public class Watcher implements Runnable {
private Film film;
public Watcher(Film film) {
super();
this.film = film;
}
@Override
public void run() {
film.watch();
}
}
MainTest.java
package FilmTest;
public class MainTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Film film = new Film();
Player player = new Player(film);
Watcher watcher = new Watcher(film);
new Thread(player).start();
new Thread(watcher).start();
}
}
执行结果如下, 出现下面内容代码还是运行状态
producer-1film-1-0
watcher-2film-1-0
producer-1film-2-1
感觉出现了死锁 ,但不知道问题出在哪里,求指教
慕姐8265434
相关分类