多线程经典之生产者与消费者

来源:互联网 发布:淘宝详情上传 编辑:程序博客网 时间:2024/05/17 06:39
<strong>package PAndC;public class C {private Service service;public void eat(Service service) throws InterruptedException{synchronized (service) {if(Service.restoreValue.equals("")){service.wait();}System.out.println("吃" + Service.restoreValue);Service.restoreValue = "";service.notify();}}}package PAndC;public class P {private Service service;public void create(Service service) throws InterruptedException{synchronized (service) {if(!Service.restoreValue.equals("")){service.wait();}String time = System.currentTimeMillis() + "";System.out.println("生产 " + time);service.restoreValue = time;service.notify();}}}package PAndC;public class Service {public static String restoreValue = "";}package PAndC;public class ThreadC extends Thread{private C c;private Service service;public ThreadC(Service service, C c){this.service = service;this.c = c;}public void run(){while(true){try {c.eat(service);} catch (InterruptedException e) {e.printStackTrace();}}}}package PAndC;public class ThreadP extends Thread{private Service service;private P p;public ThreadP(Service service, P p){this.service = service;this.p = p;}public void run(){while(true){try {p.create(service);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}package PAndC;public class TestMain {public static void main(String[] args) throws InterruptedException {Service service = new Service();P p = new P();C c = new C();ThreadC threadC = new ThreadC(service, c);threadC.start();Thread.sleep(1000);ThreadP threadP = new ThreadP(service, p);threadP.start();}}</strong>
<strong>没懂的问我下  wechat: wangyan199366</strong>


0 0
原创粉丝点击