这段代码出现线程死锁了吗?如果有是什么原因?

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

感觉出现了死锁 ,但不知道问题出在哪里,求指教


素胚勾勒不出你
浏览 468回答 2
2回答

慕姐8265434

这不是死锁啊,是你的代码有问题。你打印了producer-1film-2-1之后,flag = false,那么在你下次执行play方法的时候会执行this.wait(),并且之后它不会被唤醒,一直处于wait状态。所以之后没有任何打印信息输出。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java