java併發隊列之PriorityBlockingQueue

特色:阻塞隊列,無界隊列,固然也能夠在初始化時指定長度,會自動擴容。有優先級的概念是這個隊列的特色。採用的是升序,好比1先入對,2後入隊,出隊時2會先出隊。固然這是能夠本身改變的,重寫compareTo方法便可。java

應用場景:這個隊列仍是比較經常使用的,好比發短信,通知短信和驗證碼短信,通常驗證碼短信要最快發到客戶手中,通知類能夠慢一點無礙,有驗證碼短信優先發送。web

代碼案例:spring

package com.example.web.web;

import lombok.Data;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;

@RestController
public class HomeController {

    @RequestMapping("/index")
    public String index() throws Exception {
        PriorityBlockingQueue<PriorityElement> queue = new PriorityBlockingQueue<>();
        //生產者
        new Thread(() ->
        {
            try {
                for (int i = 0; i < 5; i++) {
                    PriorityElement priorityElement = new PriorityElement();
                    priorityElement.setAge(12);
                    priorityElement.setName("haha" + (5 - i));
                    priorityElement.setPriority(5 - i);

                    System.out.println("生產者begin");
                    queue.put(priorityElement);
                    System.out.println("生產者end");
                    TimeUnit.SECONDS.sleep(3);
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }).start();

        //消費者
        new Thread(() ->
        {
            try {
                for (int i = 0; i < 5; i++) {
                    //TimeUnit.MILLISECONDS.sleep(1000);
                    System.out.println("消費者begin");
                    PriorityElement priorityElement = queue.take();
                    //PriorityElement priorityElement = queue.poll(1, TimeUnit.SECONDS);
                    System.out.println("消費者end" + (priorityElement == null ? "null" : priorityElement.getName()));
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }).start();

        //主線程也等待下
        TimeUnit.SECONDS.sleep(20);
        return "網站已獲得響應";
    }
}

@Data
class PriorityElement implements Comparable<PriorityElement> {

    private Integer priority;
    private String name;
    private Integer age;

    public int compareTo(PriorityElement priorityElement) {
        return this.priority.compareTo(priorityElement.priority);
    }
}

添加方法除了put()還有offer(),因爲隊列長度無限制因此offer不會阻塞隊列也不會返回false,因此這兩方法效果都是同樣的。app

take()還有poll()這兩個方法和其餘隊列同樣的,用poll須要添加參數,若是不添加參數就是不等待直接獲取,獲取不到就是null值。若是有參數表示在規定時間內等待,在等待時間內有put操做則立刻返回值,超過規定時間無put操做就返回null。網站

相關文章
相關標籤/搜索