java priority_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 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:在包含字符串的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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值