这段代码出现线程死锁了吗?如果有是什么原因?
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;
}
public synchronized void watch() {
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("watcher-2"+name);
this.notify();
this.flag = true;
}
}
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
感觉出现了死锁 ,但不知道问题出在哪里,求指教
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是死锁啊,是你的代码有问题。
你打印了
producer-1film-2-1
之后,flag = false
,那么在你下次执行play
方法的时候会执行this.wait()
,并且之后它不会被唤醒,一直处于wait
状态。所以之后没有任何打印信息输出。flim.play
方法里面的wait()
等不到唤醒了