java 数据写入到队列里面-多线程获取数据
package com.thread.demo;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
public class QueueDemo {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(2);
Queue<String> queue = new LinkedList<String>();
for (int i = 0; i < 200; i++) {
queue.offer("第 " + (i + 1) + " 条数据");
}
long start = System.currentTimeMillis();
new Thread(new Runnable() {
public void run() {
while (true) {
if (queue.size() > 0) {
System.out.println(Thread.currentThread().getName() + "从队列中获取信息:" + queue.poll());
} else {
break;
}
}
latch.countDown();
}
}, "队列线程-1").start();
new Thread(new Runnable() {
public void run() {
while (true) {
if (queue.size() > 0) {
System.out.println(Thread.currentThread().getName() + "从队列中获取信息:" + queue.poll());
} else {
break;
}
}
latch.countDown();
}
}, "队列线程-2").start();
long end = System.currentTimeMillis();
try {
latch.await();
System.out.println(end - start);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}