线程通讯--BlockingQueue

Producer线程

package com.thread.communication.blockingqueue;

import java.util.concurrent.BlockingQueue;

public class Producer extends Thread{
    private BlockingQueue<String> bq;
    
    public Producer(BlockingQueue<String> bq){
        this.bq=bq;
    }
    
    public void run(){
        String[] strArr = new String[]
                {"Java","Struts","Spring"};
        for(int i=0;i<99999999;i++){
            System.out.println(getName() + "生产者准备生产集合元素");
            try{
                Thread.sleep(200);
                //如果传入的的bq的length是1,那么put一个值,就会出现阻塞现象
                bq.put(strArr[i % 3]);//求余数 0 1 2
            }catch(Exception ex){
                ex.printStackTrace();
            }
            
            System.out.println(getName()+"生产完成"+ bq);
            
        }
    }

}

Consumer线程

package com.thread.communication.blockingqueue;

import java.util.concurrent.BlockingQueue;

public class Consumer extends Thread{
    private BlockingQueue<String> bq;
    public Consumer(BlockingQueue<String> bq){
        this.bq=bq;
    }
    public void run(){
        while(true){
            System.out.println(getName()+"消费者准备消费集合元素");
            try{
                Thread.sleep(200);
                //当bq被取空时,出现阻塞
                bq.take();
            }catch(Exception ex){
                ex.printStackTrace();
            }
            System.out.println(getName()+ "消费完成"+bq);
        }
    }

}

测试类

package com.thread.communication.blockingqueue;

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

public class BlockingQueueTest {
    public static void main(String[] args){
        BlockingQueue<String> bq = new ArrayBlockingQueue<>(1);
        
        new Producer(bq).start();
        new Producer(bq).start();
        new Producer(bq).start();
        
        new Consumer(bq).start();
    }

}

 

posted @ 2016-05-17 21:44  月色深潭  阅读(225)  评论(0编辑  收藏  举报