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();
}
}
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志