zoukankan      html  css  js  c++  java
  • 线程同步之生产者与消费者

    public class Customer extends Thread{
    private Queue q;
    public Customer(Queue q){
    this.q = q;
    }

    public void run(){
    for(int i = 0; i < 10; i++){
    int value = q.get();
    }
    }
    }
    public class Producer extends Thread{
    private Queue q;
    public Producer(Queue q){
    this.q = q;
    }

    public void run(){
    for(int i = 0; i < 10; i++){
    q.put(i);

    }
    }
    }
    public class Queue {
    int value;
    boolean bFull = false;

    synchronized public void put(int i){
    if(bFull == false){
    value = i;
    bFull = true;
    System.out.println("producer put " + i);
    notify();
    }
    try{
    wait();
    }catch(Exception e){
    e.printStackTrace();
    }

    }

    synchronized public int get(){
    if(bFull == false){
    try{
    wait();
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    bFull = false;
    System.out.println("customer get " + value);
    notify();
    return value;
    }
    }
    public class TestMain {

    /**
    * @param args
    */
    public static void main(String[] args) {
    Queue q = new Queue();
    Producer p = new Producer(q);
    Customer c = new Customer(q);
    p.start();
    c.start();
    }

    }

  • 相关阅读:
    shell 格式化输出
    Linux tar 修改终端命令
    uniqu 用法
    HashMap按照value值进行排序
    汇编语言系列教程之基础入门 (一)
    Linux权限管理
    linux用户管理
    vim的tab键设定
    HTTP请求(GET与POST区别)和响应
    JS eval()
  • 原文地址:https://www.cnblogs.com/fengshaolingyun/p/6785150.html
Copyright © 2011-2022 走看看