Java如何使用LinkedBlockingQueue类?
在下面的代码片段中,您将学习如何使用LinkedBlockingQueue该类。此类实现BlockingQueue接口。我们可以通过在对象构造时指定队列容量来创建有界队列。如果我们未定义容量,则上限限制为的大小Integer.MAX_VALUE。
队列中的数据以FIFO(先进先出)顺序表示为链接节点。队列的头元素是放置在队列中的最长元素,尾元素是添加到队列中的最新元素。
让我们看看下面的代码:
package org.nhooo.example.util.concurrent;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class LinkedBlockingQueueExample {
public static void main(String[] args) {
final BlockingQueue<String> queue = new LinkedBlockingQueue<>(1024);
//生产者胎面
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
String data = UUID.randomUUID().toString();
System.out.printf("[%s] PUT [%s].%n",
Thread.currentThread().getName(), data);
queue.put(data);
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Producer").start();
//使用者1线程
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
String data = queue.take();
System.out.printf("[%s] GET [%s].%n",
Thread.currentThread().getName(), data);
Thread.sleep(550);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Consumer-1").start();
//使用者2线程
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
String data = queue.take();
System.out.printf("[%s] GET [%s].%n",
Thread.currentThread().getName(), data);
Thread.sleep(750);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "Consumer-2").start();
}
}