多线程生产者消费者问题,出现了空值,问题出在哪里?

多线程生产者消费者问题, producer生产电影(两种), customer 观看电影


Film.java


package Film;


public class Film {

    private String name;

    private String actor;

    private boolean flag = false;


    

    

    public synchronized void set(String name, String actor)

            throws InterruptedException {

        

        if(!flag){

            this.wait();

        }


        this.setName(name);

        Thread.sleep(1000);

        this.setActor(actor);


        flag = false;

        this.notify();

    }

    

    public synchronized void get() throws InterruptedException{

        

        if(flag){

            this.wait();

        }

        Thread.sleep(1000);

        System.out.println("3"+this.getName()+"-->"+this.getActor());

        flag=true;

        this.notify();

    }


    public void setName(String name) {

        this.name = name;

    }


    public void setActor(String actor) {

        this.actor = actor;

    }


    public String getName() {

        return name;

    }


    public String getActor() {

        return actor;

    }

}

Producer.java


package Film;


public class Producer implements Runnable {


    private Film film ;


    public Producer(Film film) {

        super();

        this.film = film;

    }


    @Override

    public void run() {

        // TODO Auto-generated method stub


        for (int i = 1; i < 10; i++) {


            if (0==i%2) {

                try {

                    System.out.println("1-produce film " + i);


                    film.set("film1", "actor1");

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            } else {

                try {

                    System.out.println("1-produce film " + i);

                    film.set("film2", "actor2");


                } catch (InterruptedException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }


            }


        }


    }


}


请问第二行为什么会出现空值?


幕布斯7119047
浏览 559回答 2
2回答

心有法竹

在 Film 这个代码里面,flag初始化为false,看你的 Film class 中的set, get 方法,必须先执行过 get 之后 才能执行 set。所以我觉得 File class 中 的get,set方法开头的flag判断应该是写反了吧!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java