java之多线程实例 生产者与消费者

来源:互联网 发布:伊辛模型 知乎 编辑:程序博客网 时间:2024/05/22 06:10
 1.加深线程同步操作的理解

 2.了解object类中对线程的支持方法




package ThreadTest;class Info{// 定义信息类private String name = "李兴华"; // 定义name属性private String content = "JAVA讲师"  ;// 定义content属性private boolean flag = false ;// 设置标志位public synchronized void set(String name,String content){if(!flag){try{super.wait() ;}catch(InterruptedException e){e.printStackTrace() ;}}this.setName(name) ;// 设置名称try{Thread.sleep(300) ;}catch(InterruptedException e){e.printStackTrace() ;}this.setContent(content) ;// 设置内容flag  = false ;// 改变标志位,表示可以取走super.notify() ;}public synchronized void get(){if(flag){try{super.wait() ;}catch(InterruptedException e){e.printStackTrace() ;}}try{Thread.sleep(300) ;}catch(InterruptedException e){e.printStackTrace() ;}System.out.println(this.getName() + " --> " + this.getContent()) ;flag  = true ;// 改变标志位,表示可以生产super.notify() ;}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 ;}};class Producer implements Runnable{// 通过Runnable实现多线程private Info info = null ;// 保存Info引用public Producer(Info info){this.info = info ;}public void run(){boolean flag = false ;// 定义标记位for(int i=0;i<50;i++){if(flag){this.info.set("李兴华","JAVA讲师") ;// 设置名称flag = false ;}else{this.info.set("mldn","www.mldnjava.cn") ;// 设置名称flag = true ;}}}};class Consumer implements Runnable{private Info info = null ;public Consumer(Info info){this.info = info ;}public void run(){for(int i=0;i<50;i++){this.info.get() ;}}};public class demo1{public static void main(String args[]){Info info = new Info();// 实例化Info对象Producer pro = new Producer(info) ;// 生产者Consumer con = new Consumer(info) ;// 消费者new Thread(pro).start() ;new Thread(con).start() ;}};



0 0