多线程问题(生产者和消费者)

来源:互联网 发布:下载淘宝助理免费 编辑:程序博客网 时间:2024/06/06 02:53

class Message {

           privateString title;

           privateString content;

           privateboolean flag = true;

           //flag == true:表示可以生产,但是不能取走

           //flag == false:表示可以取走,但是不能生产

           publicsynchronized void set(String title, String content) {

                     if(this.flag == false) {                                            //已经生产过了,不能生产

                                try{

                                          super.wait();                                                   //等待

                                }catch (InterruptedException e) {

                                          e.printStackTrace();

                                }

                     }

                     this.title= title;

                     try{

                                Thread.sleep(200);

                     }catch (InterruptedException e) {

                                e.printStackTrace();

                     }

                     this.content= content;

                     this.flag= false;                                                      //已经生产完成,修改标志位

                     super.notify();                                                                     //唤醒等待线程

           }

           public synchronized void get() {

                     if(this.flag == true) {                                              //未生产,不能取走

                                try{

                                          super.wait();                                                   //等待

                                }catch (InterruptedException e) {

                                          e.printStackTrace();

                                }

                     }

                     try{

                                Thread.sleep(100);

                     }catch (InterruptedException e) {

                                e.printStackTrace();

                     }

                     System.out.println(this.title+ " --> " +this.content);

                     this.flag = true;                                                       //已经取走了,可以继续生产

                     super.notify();                                                                     //唤醒等待线程

           }

           // setter、getter略

}

}

}
原创粉丝点击