说明
LinkedBlockingQueue
是 Java 并发包 java.util.concurrent
中的一个阻塞队列。它内部使用链表实现,并且是线程安全的
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| package org.jeecg.modules.netty.tcp;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit;
public class LinkedBlockingQueueExample {
public static void main(String[] args) { LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(10);
Thread producerThread = new Thread(new Producer(queue)); producerThread.start();
try { TimeUnit.MILLISECONDS.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); }
Thread consumerThread = new Thread(new Consumer(queue)); consumerThread.start(); }
static class Producer implements Runnable { private final LinkedBlockingQueue<String> queue;
Producer(LinkedBlockingQueue<String> queue) { this.queue = queue; }
@Override public void run() { try { for (int i = 0; i < 20; i++) { String message = "Message-" + i; System.out.println("Producing: " + message);
queue.offer(message, 1000, TimeUnit.MILLISECONDS);
TimeUnit.MILLISECONDS.sleep(1000); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
static class Consumer implements Runnable { private final LinkedBlockingQueue<String> queue;
Consumer(LinkedBlockingQueue<String> queue) { this.queue = queue; }
@Override public void run() { try { while (true) {
String message = queue.poll(1000, TimeUnit.MILLISECONDS); System.out.println("Consuming: " + message);
TimeUnit.MILLISECONDS.sleep(500); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } }
|