---
title: "可阻塞的队列"
author: "youyang_java"
date: "2014-05-09T14:46:40Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-05-09T15:18:47Z"
id: 2064332
url: "https://youyang-java.iteye.com/blog/2064332"
---

l什么是可阻塞队列，阻塞队列的作用与实际应用，阻塞队列的实现原理。

l阻塞队列与Semaphore有些相似，但也不同，阻塞队列是一方存放数据，另一方释放数据，Semaphore通常则是由同一方设置和释放信号量。

lArrayBlockingQueue

Ø只有put方法和take方法才具有阻塞功能

l用3个空间的队列来演示阻塞队列的功能和效果。

l用两个具有1个空间的队列来实现同步通知的功能。

 

public static void main(String\[] args) {  
  final BlockingQueue queue = new ArrayBlockingQueue(3);  
  for(int i=0;i&lt;2;i++){  
   new Thread(){  
    public void run(){  
     while(true){  
      try {  
       Thread.sleep((long)(Math.random()\*1000));  
       System.out.println(Thread.currentThread().getName() + "准备放数据!");         
       queue.put(1);  
       System.out.println(Thread.currentThread().getName() + "已经放了数据，" +          
          "队列目前有" + queue.size() + "个数据");  
      } catch (InterruptedException e) {  
       e.printStackTrace();  
      }

     }  
    }  
      
   }.start();  
  }  
    
  new Thread(){  
   public void run(){  
    while(true){  
     try {  
      //将此处的睡眠时间分别改为100和1000，观察运行结果  
      Thread.sleep(1000);  
      System.out.println(Thread.currentThread().getName() + "准备取数据!");  
      queue.take();  
      System.out.println(Thread.currentThread().getName() + "已经取走数据，" +          
        "队列目前有" + queue.size() + "个数据");       
     } catch (InterruptedException e) {  
      e.printStackTrace();  
     }  
    }  
   }  
     
  }.start();     
 }