e2

滴滴侠,fai抖

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

示例代码:

package model;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;



class 生产者 implements Runnable{
    
    private BlockingQueue<String> drop;
    private List<String> messages =Arrays.asList("aaaaa","bbbbb","ccccc","ddddd","eeeee");

    public 生产者(BlockingQueue<String> d){
        this.drop=d;
    }
    
    public void run() {
        try {
            for(String s:messages){
                System.out.println("--------------"+s);
                drop.put(s);
            }
            drop.put("完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

class 消费者 implements Runnable{

    private BlockingQueue<String> drop;
    
    public 消费者(BlockingQueue<String> d){
        this.drop=d;
    }
    
    public void run() {
        try {
            String msg;
            while(!((msg = drop.take()).equals("完成"))){
                System.out.println(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
}

public class 生产者消费者 {
    
    public static void main(String[] args) {
        BlockingQueue<String> drop=new ArrayBlockingQueue<String>(3,true);
        new Thread(new 生产者(drop)).start();
        new Thread(new 消费者(drop)).start();
    }
    
}

 

posted on 2017-07-30 21:02  纯黑Se丶  阅读(108)  评论(0编辑  收藏  举报