Java 实现生产者与消费者(二)

来源:互联网 发布:读写加密锁软件 编辑:程序博客网 时间:2024/04/30 16:56

       在上篇博客中简单实现了生产者与消费者之间的通信,本片博客讲的是在实际开发当中是怎样实现二者之间的通信的。实际开发中将生产与消费的环节封装成函数放在了resource里面,这样在生产与消费的时候就更加的便捷,提高了代码的复用性。代码如下:

package threadCommunication;//生产者和消费者共享的资源class Resource{String name;String sex;boolean flag=false;//将生产的环节封装成resource里面,并且封装成同步函数public synchronized void produce(String name,String sex){if(flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}this.name=name;this.sex=sex;System.out.println("输入:"+name+"性别:"+sex);this.flag=true;this.notify();}//同理将消费者封装到resource里面,封装成同步函数public synchronized void consume(){if(!flag){try {this.wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println("输出:"+this.name+"性别:"+this.sex);this.flag=false;this.notify();}}//输入,代表的是生产者class Input implements Runnable{Resource r;Input(Resource r){this.r=r;}public void run() {int x=1;while(true){r.produce("小光"+x, "男");x++;if(x>10)x=1;}}}//输出,代表的是消费者 class Output implements Runnable{Resource r;Output(Resource r){this.r=r;}public void run() {while(true){r.consume();}}}public class InputOutput2 {/** * @param args *  */public static void main(String[] args) {Resource r=new Resource();Input in=new Input(r);Output out=new Output(r);new Thread(in).start();new Thread(out).start();}}
运行结果如下:

0 0
原创粉丝点击