`
墙头上一根草
  • 浏览: 150030 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java 生产者消费者例子

    博客分类:
  • java
阅读更多

用synchronized wait及notify实现  简单的生产者消费者的例子。以下是代码部分

 

/**    
* Test.java Create on 2014年10月10日   
*    
* Copyright (c) 2014年10月10日 by dzh
*    
* @author <a href="xingyu@gw.com.cn">xingyu</a>   
* @version 0.0.1
*   
*/
package org.dzh.thread.waitAndnotify;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**@className:Test.java

 * @description
 * 线程{@link Thread} 与{@link Object#notify() #wait()} 的用法例子
 * 简单生产者消费者例子

 * @date 2014年10月10日 上午11:32:23
 */
public class Test {

    private static List<Integer> queue = new ArrayList<>();
   
   
    /**
     * 生产者
     * @param n     void
     *    
     */
    public synchronized void producer(int n){
        System.out.println("insert data "+n);
        queue.add(n);
       
        if(queue.size()==1)
            this.notify();
    }
   
    /**
     * 消费者
     * @return     int
     *    
     */
    public synchronized int consumer(){
            try {
                if(queue.isEmpty())
                    this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        int result = queue.get(0);
        queue.remove(0);
        return result;
    }
   
    public static void main(String[] args) {
        final Test test = new Test();
       
        Thread thread1 = new Thread(new Runnable() {//生产线程
           
            @Override
            public void run() {
                Random random = new Random();
                try {
                    while(true){
                        test.producer(random.nextInt(1000));
                        Thread.sleep(2000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
       
        Thread thread2 = new Thread(new Runnable() {//消费线程
           
            @Override
            public void run() {
                try {
                    while(true){
                        System.out.println("select data is "+test.consumer());
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
       
        thread1.start();
        thread2.start();
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics