當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java PriorityBlockingQueue take()用法及代碼示例


PriorityBlockingQueue的take()方法在刪除隊列後將其返回。如果queue為空,則此方法將等待直到元素可用。

用法:

public E take() throws InterruptedException

返回值:此方法返回此PriorityBlockingQueue開頭的值。


異常:如果在等待元素可用時被中斷,則此方法將引發InterruptedException。

下麵的程序說明PriorityBlockingQueue的take()方法:

示例1:演示PriorityBlockingQueue上的take()方法,該方法包含數字列表。

// Java Program Demonstrate take() 
// method of PriorityBlockingQueue 
  
import java.util.concurrent.PriorityBlockingQueue; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
        throws InterruptedException 
    { 
  
        // create object of PriorityBlockingQueue 
        PriorityBlockingQueue<Integer> PrioQueue 
            = new PriorityBlockingQueue<Integer>(); 
  
        // Add numbers to PriorityBlockingQueue 
        PrioQueue.put(7855642); 
        PrioQueue.put(35658786); 
        PrioQueue.put(5278367); 
        PrioQueue.put(74381793); 
  
        // before removing print queue 
        System.out.println("Queue: " + PrioQueue); 
  
        // Apply take() method 
        int head = PrioQueue.take(); 
  
        // Print head of queue using take() method 
        System.out.println("Head of PriorityBlockingQueue"
                           + " using take(): " + head); 
  
        System.out.print("After removing head, Queue: "
                         + PrioQueue); 
    } 
}
輸出:
Queue: [5278367, 35658786, 7855642, 74381793]
Head of PriorityBlockingQueue using take(): 5278367
After removing head, Queue: [7855642, 35658786, 74381793]

示例2:在包含字符串的PriorityBlockingQueue上演示take()方法

// Java Program Demonstrate take() 
// method of PriorityBlockingQueue 
  
import java.util.concurrent.PriorityBlockingQueue; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
        throws InterruptedException 
    { 
  
        // create object of PriorityBlockingQueue 
        // which contains Strings 
        PriorityBlockingQueue<String> names 
            = new PriorityBlockingQueue<String>(); 
  
        // Add string 
        names.add("Geeks"); 
        names.add("forGeeks"); 
        names.add("A computer portal"); 
  
        // print list of names 
        System.out.println(names); 
  
        // Apply take() method 
        String head = names.take(); 
  
        // Print head of queue using take() method 
        System.out.println("Head of Queue: "
                           + head); 
        System.out.print("After removing head, Queue: "
                         + names); 
    } 
}
輸出:
[A computer portal, forGeeks, Geeks]
Head of Queue: A computer portal
After removing head, Queue: [Geeks, forGeeks]

參考: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html#take–



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 PriorityBlockingQueue take() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。