Film.javapackage 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.javapackage 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.javapackage FilmTest;public class Watcher implements Runnable { private Film film; public Watcher(Film film) { super(); this.film = film; } @Override public void run() { film.watch(); }}MainTest.javapackage 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-0watcher-2film-1-0producer-1film-2-1感觉出现了死锁 ,但不知道问题出在哪里,求指教
2 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
这不是死锁啊,是你的代码有问题。
你打印了producer-1film-2-1
之后,flag = false
,那么在你下次执行play
方法的时候会执行this.wait()
,并且之后它不会被唤醒,一直处于wait
状态。所以之后没有任何打印信息输出。
添加回答
举报
0/150
提交
取消