线程生产者与消费者

来源:互联网 发布:仓库,财务办公软件 编辑:程序博客网 时间:2024/05/16 09:38

线程出现重复取和重复赋值的情况

class Info{private String name;private String content;public void setName(String name){this.name = name ;}public void setContent(String content){this.content = content ;}public String getName(){return this.name ;}public String getContent(){return this.content ;}public synchronized void set(String name, String content){this.setName(name);try{Thread.sleep(300);}catch(Exception e){e.printStackTrace();}this.setContent(content);}public synchronized void get(){try{Thread.sleep(300);}catch(Exception e){e.printStackTrace();}System.out.println(this.getName() + "<--->" + this.getContent());}}class Producer implements Runnable{private Info info;public Producer(Info info){this.info = info;}@Overridepublic void run(){boolean flag = false;for (int i=0;i<50 ;i++ ){if(flag){this.info.set("123", "789");flag = false;}else{this.info.set("abc", "xyz");flag = true;}}}}class Consumer implements Runnable{private Info info;public Consumer(Info info){this.info = info;}@Overridepublic void run(){for(int i=0;i<50 ;i++ ){this.info.get();}}}public class T3 {public static void main(String[] args) {Info info = new Info();Producer pro = new Producer(info);Consumer con = new Consumer(info);new Thread(pro).start();new Thread(con).start();}}



利用Object类的wait()和notify()方法

class Info{private String name = "123";private String content = "789";private boolean flag = false;public void setName(String name){this.name = name ;}public void setContent(String content){this.content = content ;}public String getName(){return this.name ;}public String getContent(){return this.content ;}public synchronized void set(String name, String content){if(!flag){try{super.wait();}catch(Exception e){e.printStackTrace();}}this.setName(name);try{Thread.sleep(300);}catch(Exception e){e.printStackTrace();}this.setContent(content);flag = !flag;super.notify();}public synchronized void get(){if(flag){try{super.wait();}catch(Exception e){e.printStackTrace();}}try{Thread.sleep(300);}catch(Exception e){e.printStackTrace();}System.out.println(this.getName() + "<--->" + this.getContent());flag = !flag;super.notify();}}class Producer implements Runnable{private Info info;public Producer(Info info){this.info = info;}@Overridepublic void run(){boolean flag = false;for (int i=0;i<50 ;i++ ){if(flag){this.info.set("123", "789");flag = false;}else{this.info.set("abc", "xyz");flag = true;}}}}class Consumer implements Runnable{private Info info;public Consumer(Info info){this.info = info;}@Overridepublic void run(){for(int i=0;i<50 ;i++ ){this.info.get();}}}public class T4 {public static void main(String[] args) {Info info = new Info();Producer pro = new Producer(info);Consumer con = new Consumer(info);new Thread(pro).start();new Thread(con).start();}}




原创粉丝点击