通过实例了解java TransferQueue

序言

本文主要简介一下TransferQueue。

TransferQueue

TransferQueue(java7引入)继承了BlockingQueue(BlockingQueue又继承了Queue)并扩展了一些新方法。生产者会一直阻塞直到所添加到队列的元素被某一个消费者所消费(不仅仅是添加到队列里就完事)。

LinkedTransferQueue

LinkedTransferQueue实际上是ConcurrentLinkedQueue、SynchronousQueue(公平模式)和LinkedBlockingQueue的超集。而且LinkedTransferQueue更好用,因为它不仅仅综合了这几个类的功能,同时也提供了更高效的实现。

对比SynchronousQueue

SynchronousQueue使用两个队列(一个用于正在等待的生产者、另一个用于正在等待的消费者)和一个用来保护两个队列的锁。而LinkedTransferQueue使用CAS操作实现一个非阻塞的方法,这是避免序列化处理任务的关键。

使用场景

当我们不想生产者过度生产消息时,TransferQueue可能非常有用,可避免发生OutOfMemory错误。在这样的设计中,消费者的消费能力将决定生产者产生消息的速度。

实例

public class LinkedTransferQueueDemo {

static LinkedTransferQueue<String> lnkTransQueue = new LinkedTransferQueue<String>();

public static void main(String[] args) {

ExecutorService exService = Executors.newFixedThreadPool(2);

Producer producer = new LinkedTransferQueueDemo().new Producer();

Consumer consumer = new LinkedTransferQueueDemo().new Consumer();

exService.execute(producer);

exService.execute(consumer);

exService.shutdown();

}

class Producer implements Runnable{

@Override

public void run() {

for(int i=0;i<3;i++){

try {

System.out.println("Producer is waiting to transfer...");

lnkTransQueue.transfer("A"+i);

System.out.println("producer transfered element: A"+i);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

class Consumer implements Runnable{

@Override

public void run() {

for(int i=0;i<3;i++){

try {

System.out.println("Consumer is waiting to take element...");

String s= lnkTransQueue.take();

System.out.println("Consumer received Element: "+s);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

}

输出

Producer is waiting to transfer...

Consumer is waiting to take element...

producer transfered element: A0

Producer is waiting to transfer...

Consumer received Element: A0

Consumer is waiting to take element...

producer transfered element: A1

Producer is waiting to transfer...

Consumer received Element: A1

Consumer is waiting to take element...

Consumer received Element: A2

producer transfered element: A2

以上是 通过实例了解java TransferQueue 的全部内容, 来源链接: utcz.com/z/332717.html

回到顶部