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();
    }

    }

  • 相关阅读:
    gnats配置文件
    在Mac中安装python,配置python环境
    利用git bash和git gui向git远程仓库提交文件
    os模块
    django中的locale()函数
    django配置静态文件
    sso单点登录
    django get_object_or_404
    关于token
    Django的CSRF机制
  • 原文地址:https://www.cnblogs.com/fengshaolingyun/p/6785150.html
Copyright © 2011-2022 走看看