请用java代码的方式写出使用阻塞队列的实现
时间: 2024-05-02 08:18:21 浏览: 21
以下是使用阻塞队列实现的示例代码:
```java
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class BlockingQueueExample {
public static void main(String[] args) throws InterruptedException {
// 创建一个大小为10的阻塞队列
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
// 生产者线程
Thread producerThread = new Thread(() -> {
try {
for (int i = 1; i <= 20; i++) {
// 将数据放入队列中
queue.put(i);
System.out.println("生产者放入数据:" + i);
Thread.sleep(500); // 休眠500毫秒
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 消费者线程
Thread consumerThread = new Thread(() -> {
try {
for (int i = 1; i <= 20; i++) {
// 从队列中取出数据
int data = queue.take();
System.out.println("消费者取出数据:" + data);
Thread.sleep(1000); // 休眠1秒
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 启动线程
producerThread.start();
consumerThread.start();
// 等待线程执行完毕
producerThread.join();
consumerThread.join();
}
}
```
在上面的示例中,我们使用了 `ArrayBlockingQueue` 来创建一个大小为10的阻塞队列。生产者线程不断往队列中放入数据,直到放入了20个数据为止;消费者线程不断从队列中取出数据,直到取出了20个数据为止。由于队列是阻塞的,当队列为空时,消费者线程将被阻塞,直到有数据可取;当队列已满时,生产者线程将被阻塞,直到有空间可用。通过这种方式,我们可以很方便地实现线程间的数据传输。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)