多线程之解决数据错位问题

class Message{

         private String title;

         private String content;

        

         public synchronized void set(Stringtitle,String content){

                   this.title = title;

                   try {

                            Thread.sleep(100);

                   } catch (InterruptedExceptione) {

                            e.printStackTrace();

                   }

                   this.content = content;

         }

        

         public synchronized void get(){

                   try {

                            Thread.sleep(100);

                   } catch (InterruptedExceptione) {

                            e.printStackTrace();

                   }

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

         }

}

 

class Productorimplements Runnable{

         private Message msg = null;

         public Productor(Message msg){

                   this.msg = msg;

         }

        

         @Override

         public void run(){

                   for(int i = 0;i < 50;i++){

                            if(i % 2 == 0){

                                     this.msg.set("2012-12-21","世界末日");

                            }

                            else{

                                     this.msg.set("付谢", "打扫卫生迎接末日");

                            }

                   }

         }

}

 

class Customerimplements Runnable{

         private Message msg = null;

         public Customer(Message msg){

                   this.msg = msg;

         }

        

         @Override

         public void run(){

                   for(int i = 0;i < 50;i++){

                            this.msg.get();

                   }

         }

}

        

public classTestDemo3{

         public static void main(String[] args){

                   Message msg = new Message();

                   new Thread(newProductor(msg)).start();

                   new Thread(newCustomer(msg)).start();

         }

}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。