zoukankan      html  css  js  c++  java
  • 线程:单生产者单消费者

    /**
     * 单生产者单消费者
     * 一个生产线成一个消费线程
     * 一个生产任务一个消费任务
     * 一个产品
     */
    public class Demo5 {
        public static void main(String[] args) {
        //产品类的对象 P p
    = new P(); //创建任务类的对象 Producer producer3 = new Producer(p); Consumer consumer3 = new Consumer(p); //创建线程 Thread t0 = new Thread(producer3); Thread t1 = new Thread(consumer3); //开启线程 t0.start(); t1.start(); } } //产品类 class P {
    //产品类的属性:名字、价格、产品数量 String name;
    double price; int count;
    //标识
    boolean flag = false; //负责生产 public synchronized void setP(String name, double price) { if (flag == true) { try { wait(); //让生产线等待 } catch (InterruptedException e) { e.printStackTrace(); } } this.name = name; this.price = price; System.out.println(Thread.currentThread().getName() +" 生产了:"+this.name +" 产品数量:"+ this.count +" 产品价格:"+ this.price); count++; flag = ! flag; notify(); //唤醒消费线程 } //负责消费 public synchronized void getP() { if(flag == false) { try { wait(); //让消费线程等待 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() +" 消费了:"+this.name +" 产品数量:"+ this.count +" 产品价格:"+ this.price); flag = !flag; notify(); //唤醒生产线程 } } //生产线程 class Producer implements Runnable{ P p; public Producer(P p) { this.p = p; } @Override public void run() { while(true) { p.setP("冰冰", 20); } } } //消费线程 class Consumer implements Runnable{ P p; public Consumer(P p) { this.p = p; } @Override public void run() { while(true) { p.getP(); } } }
  • 相关阅读:
    Beyond Compare比较图片怎么修改背景颜色
    Leonardo's Notebook UVALive
    Saddle Point ZOJ
    概率dp总结 正在更新
    First Knight UVALive
    Scout YYF I POJ
    RedIsGood TopCoder
    聪聪和可可 HYSBZ
    So you want to be a 2n-aire? UVA
    国家队论文集
  • 原文地址:https://www.cnblogs.com/yumengfei/p/11012113.html
Copyright © 2011-2022 走看看