juc之阻塞隊列

什麼是阻塞隊列?

當隊列爲空時,從隊列中獲取元素將阻塞。

當隊列爲滿時,從隊列中添加元素將阻塞。

 

爲什麼需要阻塞隊列,有什麼好處?

在多線程領域:所謂阻塞,在某些條件下會掛起線程(即阻塞),一旦條件滿足,掛起的線程又會自動被喚醒。

好處是我們不需要關係什麼時候阻塞隊列,什麼時候喚醒隊列,這一切BlockingQueue已經包裝好了,concurrent包發佈以前需要自己手動去控制這些細節。

 

 

 add方法,當添加元素滿時再添加會報錯。

remove方法,當隊列空時,再移除會報錯。 

 element方法,用來檢驗當前元素,如果爲空會報錯,不爲空會取出當前元素,隊列不會移除還會存在。

使用offer方法,如果插入不進去了等待兩秒返回false。

同步隊列,只能存儲一個。 

package com.example.demo;

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

public class ArrayBlockingQueueDemo {

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new SynchronousQueue<>();

        new Thread(()->{
            try {
                queue.put("1");
                System.out.println(Thread.currentThread().getName()+":put 1");
                queue.put("2");
                System.out.println(Thread.currentThread().getName()+":put 2");
                queue.put("3");
                System.out.println(Thread.currentThread().getName()+":put 3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"AA").start();
        new Thread(()->{
            try {
                queue.take();
                System.out.println(Thread.currentThread().getName()+":take 1");
                queue.take();
                System.out.println(Thread.currentThread().getName()+":take 2");
                queue.take();
                System.out.println(Thread.currentThread().getName()+":take 3");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"BB").start();

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章