读书人

多线程(1)生产者消费者有关问题!(

发布时间: 2012-08-29 08:40:14 作者: rapoo

多线程(1)生产者消费者问题!!!(原创)

package test;/** * @author  E-mail:xhf@126.com * @version 创建时间:2011-11-21 上午09:14:58 * 类说明 */public class CaoYang {static public void main(String[] args){Loufeng loufeng=new Loufeng(3) ;new XiaoJie("嘉新",loufeng,1000).start() ;new XiaoJie("萝莉",loufeng,1000).start() ;new XiaoJie("诗情",loufeng,1000).start() ;new KeRen("张三",loufeng,1000).start() ;new KeRen("李四",loufeng,1000).start() ;new KeRen("王五",loufeng,1000).start() ;}}
?package test;
import java.util.Random;/** * @author E-mail:xhf@126.com * @version 创建时间:2011-11-21 上午09:14:04 * 类说明 */public class KeRen extends Thread{private final Random random ;private final Loufeng loufeng ;public KeRen(String name ,Loufeng loufeng,long l){super(name) ;this.loufeng=loufeng ;random=new Random(l) ;}public void run(){try{while(true){String cake=loufeng.get() ;System.out.println("完成交易:"+cake) ;Thread.sleep(random.nextInt(1000)) ;}}catch(Exception e){e.printStackTrace() ;}}}

?package test;

/** * @author  E-mail:xhf@126.com * @version 创建时间:2011-11-21 上午09:14:42 * 类说明  */public class Loufeng {private int count ;private int zou  ;//当前要出台的private  int hui ;//当前新回来的private final String buffer[] ;public Loufeng(Integer sum){this.buffer=new String[3] ;this.count=0 ;this.zou=0 ;this.hui=0 ;}public synchronized void put(String xiaoj) throws InterruptedException{System.out.println(Thread.currentThread().getName()+xiaoj) ;while(count>=buffer.length){wait() ;}buffer[hui]=xiaoj ;hui=(hui+1)%buffer.length ;count++ ;System.out.println("库存量=============="+count) ;this.notifyAll() ;}public synchronized String get() throws InterruptedException{while(count<=0){wait() ;}String taak=buffer[zou] ;zou=(zou+1)%buffer.length ;count-- ;this.notifyAll() ;System.out.println(Thread.currentThread().getName()+"准备带走"+taak) ;return taak; }}

?package test;

import java.util.Random;/** * @author  E-mail:xhf@126.com * @version 创建时间:2011-11-21 上午09:20:59 * 类说明 */public class XiaoJie extends Thread{private final Random random ;private final Loufeng  loufeng ;private static int i=0 ;public XiaoJie(String name ,Loufeng loufeng,long feed){super(name) ;this.loufeng=loufeng ;this.random=new Random(feed) ;}public void run(){while(true){try {Thread.sleep(random.nextInt(1000)) ;String cha="序号"+getid()+"===姓名:"+this.getName();loufeng.put(cha) ;} catch (InterruptedException e) {e.printStackTrace();}}}public static final int getid(){return i++ ;}}

?

?

?

读书人网 >编程

热点推荐