写一个java代码多线程应用顺序读取concurrentlinkedqueue
时间: 2023-06-09 17:08:31 浏览: 120
Java多线程按指定顺序同步执行
好的,这是一个实现多线程应用顺序取 ConcurrentLinkedQueue 的 Java 代码示例:
`
import java.util.concurrent.ConcurrentLinkedQueue;
public class QueueReader implements Runnable {
private ConcurrentLinkedQueue<String> queue;
private Object lock;
public QueueReader(ConcurrentLinkedQueue<String> queue, Object lock) {
this.queue = queue;
this.lock = lock;
}
public void run() {
try {
synchronized(lock) {
while (true) {
while (!queue.isEmpty()) {
String item = queue.poll();
System.out.println(Thread.currentThread().getName() + " read item: " + item);
}
lock.notifyAll();
lock.wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<String>();
Object lock = new Object();
QueueReader reader1 = new QueueReader(queue, lock);
QueueReader reader2 = new QueueReader(queue, lock);
Thread thread1 = new Thread(reader1, "Thread 1");
Thread thread2 = new Thread(reader2, "Thread 2");
thread1.start();
thread2.start();
// Add items to the queue
queue.offer("Item 1");
queue.offer("Item 2");
queue.offer("Item 3");
// Wait for the threads to finish
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
这个示例中,我们创建了一个 ConcurrentLinkedQueue 对象和两个 QueueReader 线程。每个 QueueReader 线程都会不断从队列中取出元素并输出到控制台。通过 lock 对象实现线程同步,确保每个线程顺序读取队列中的元素。在主线程中添加了一些元素到队列中,并等待两个子线程执行完毕。
阅读全文