zoukankan      html  css  js  c++  java
  • JAVA_Thread_生产消费模式

    package com.kk.thread;

    public class Test {
    public static void main(String[] args) {
    Queue q=new Queue();
    Producer p=new Producer(q);
    Consumer c=new Consumer(q);
    c.start();
    p.start();
    }
    }

    class Producer extends Thread {
    Queue q;
    public Producer(Queue q) {
    this.q=q;
    }
    public void run() {
    for (int i = 0; i < 10; i++) {
    q.put(i);
    System.out.println("q.put(i)=="+i);
    }
    }
    }

    class Consumer extends Thread {
    Queue q;
    public Consumer(Queue q) {
    this.q=q;
    }
    public void run() {
    while(true)
    System.out.println("q.get(i)=="+q.get());
    }
    }

    class Queue {
    int i;
    boolean bFull;
    public synchronized void put(int i) {
    if(!bFull){ //如果队列里面没有值
    this.i = i; //给队列添加值
    bFull=true; //设置为有值
    notify(); //唤醒等待队列
    }
    try {
    wait(); //无论有没有进入if ,此时bFull为true,表示有值,则线程等待,让Consumer取。
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }

    public synchronized int get() {
    if(!bFull){//如果bFull没有值
    try {
    wait();//则让线程等待,让Producer放入值
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    notify(); //此时表示bFull里面有值,要唤醒Pruducer继续放入值
    bFull=false; //设置bFull为没有值,因为后面将会取走i的值
    return i;
    }
    }



  • 相关阅读:
    文本框样式
    flash载入xml不显示中文之谜
    日期 时间 正则表达式
    .NET对象生命周期小结
    Python标准库12 数学与随机数 (math包,random包)
    CXF 4 应用开发
    CXF 2
    CXF 3
    MyEclipse提示键配置、提示快捷键、提示背景色、关键字颜色、代码显示
    CXF 5参考资料
  • 原文地址:https://www.cnblogs.com/BigIdiot/p/2290440.html
Copyright © 2011-2022 走看看