java 线程-一对一生产者消费者

来源:互联网 发布:js获取手机当前位置 编辑:程序博客网 时间:2024/06/04 19:46

线程中生产者消费者是一个经典问题, 也是一个难点问题,下边写一段1对1的生产者消费者代码:

package com.mjlf.myBatis.thread;/** * Created by a123 on 17/2/18. * 一对一生产者消费者 */public class PC {    private String value = "";    class P {        private PC lock;        public P(PC lock) {            super();            this.lock = lock;        }        public void create() {            try {                synchronized (this.lock) {                    Thread.sleep(1000);                    if (!"".equals(value)) {                        this.lock.wait();                    }                    System.out.println("create");                    value = "create";                    this.lock.notify();                }            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    class C {        private PC lock;        public C(PC lock) {            super();            this.lock = lock;        }        public void direc() {            try {                synchronized (this.lock) {                    Thread.sleep(1000);                    if ("".equals(value)) {                        this.lock.wait();                    }                    System.out.println("direc");                    value = "";                    this.lock.notify();                }            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }    class ThreadP implements Runnable {        private P p;        public ThreadP(P p) {            this.p = p;        }        public void run() {            while (true) {                this.p.create();            }        }    }    class ThreadC implements Runnable {        private C c;        public ThreadC(C c) {            this.c = c;        }        public void run() {            while (true) {                this.c.direc();            }        }    }    public static void main(String[] args){        PC pc = new PC();        P p = pc.new P(pc);        C c = pc.new C(pc);        Thread threadP = new Thread(pc.new ThreadP(p));        Thread threadC = new Thread(pc.new ThreadC(c));        threadC.start();        threadP.start();    }}//结果:/**createdireccreatedireccreatedireccreate*/

代码解释:
为了在同一个文件中写,该样例使用了内部类。其中根据value变量的值判断当前是该生产还是该消费, P类是生产类,C类是消费类, 同样ThreadP是生产线程,ThreadC是消费线程, 当判断value值为“”时,消费线程wait,当判断value值不为“”时,生产线程wait,每次执行生产或消费后都需要将另一个等待线程notify,否则线程将永远等待下去。

0 0