📌  相关文章
📜  Java中的 PriorityBlockingQueue take() 方法

📅  最后修改于: 2022-05-13 01:54:53.848000             🧑  作者: Mango

Java中的 PriorityBlockingQueue take() 方法

PriorityBlockingQueuetake()方法在移除队列后返回队列的头部。如果队列为空,则此方法将等待直到元素可用。

句法:

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 PrioQueue
            = new PriorityBlockingQueue();
  
        // 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:演示包含 String 的 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 names
            = new PriorityBlockingQueue();
  
        // 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: Java/util/concurrent/PriorityBlockingQueue.html#take–