Java LinkedTransferQueue getWaitingConsumerCount()方法及示例
java.util.concurrent.LinkedTransferQueue .getWaitingConsumerCount() 方法返回等待通过take()或定时轮询从LinkedTransferQueue(LTQ)接收元素的消费者数量。这里的消费者将从LTQ中读取元素。生产者将把元素添加到LTQ中。这个方法只有在多线程运行时才有用,也就是说,生产者正在传输消息,而消费者正在同时接收它们。消费者将尝试读取LTQ的头部。如果他们不能(空的LTQ或头部已经被占用),他们被称为等待。消费者将等待,直到他们读到头部,或直到一定的时间限制过了。当一个生产者通过transfer()向LTQ添加时,它被称为被阻塞。这意味着生产者必须等待,直到有消费者读取该元素,才能向LTQ中添加另一个元素。
语法
public int getWaitingConsumerCount()
参数: 该方法不接受任何参数。
返回值: 该方法返回一个int值,它是通过take()获得的等待LTQ头部的消费者的数量。
例子: 下面的程序使用一个生产者和3个消费者。生产者发送了3条信息。首先调用take()的消费者将收到最新的消息。因此,这个程序的不同执行会导致不同的消费者获得不同的消息。
// Java program to show LinkedTransferQueue
// getWaitingConsumerCount() method
import java.util.concurrent.*;
public class GFG {
// create object of LinkedTransferQueue
LinkedTransferQueue<Integer> LTQ
= new LinkedTransferQueue<>();
class Producer implements Runnable {
@Override
public void run()
{
for (int i = 0; i < 3; i++) {
try {
System.out.println("Producer is"
+ " waiting to transfer...");
// add 0, 1, 2 to LTQ
LTQ.transfer(i);
System.out.println("Producer "
+ "transferred element: " + i);
// display how many consumers are waiting
// after producer has transferred element
System.out.println("Waiting consumer "
+ "count after transfer: "
+ LTQ
.getWaitingConsumerCount());
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
int id;
Consumer(int id)
{
this.id = id;
}
@Override
public void run()
{
try {
System.out.println("Consumer "
+ id
+ " is waiting to "
+ "take element...");
// display how many consumers are waiting
// before a consumer has taken element from LTQ
System.out.println("Waiting consumer"
+ " count before take: "
+ LTQ
.getWaitingConsumerCount());
Integer s = LTQ.take();
System.out.println("Consumer "
+ id
+ " received Element: "
+ s);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException
{
// class object to keep common LTQ for all consumers
//(alternative: LTQ can be declared static)
GFG obj = new GFG();
// enabling multiple threads
ExecutorService exService
= Executors.newFixedThreadPool(3);
// declare one producer and 3 consumers
Producer producer = obj.new Producer();
Consumer consumer0 = obj.new Consumer(0);
Consumer consumer1 = obj.new Consumer(1);
Consumer consumer2 = obj.new Consumer(2);
// start producer and consumers
exService.execute(producer);
exService.execute(consumer0);
exService.execute(consumer1);
exService.execute(consumer2);
// stop
exService.shutdown();
}
}
输出:
注: 显示的是NetBeans 8.2中的输出。建议在本地尝试这个例子,因为它使用了多线程。在线的IDE服务器可能不支持或者不让你增加这样的负载,导致超过时间限制的错误。
参考资料 :https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/LinkedTransferQueue.html#getWaitingConsumerCount-