Skip to content

Commit

Permalink
JAVA源码解析 增加队列的一些理论知识
Browse files Browse the repository at this point in the history
  • Loading branch information
0xcaffebabe committed Feb 23, 2020
1 parent 18c5550 commit bd4d46a
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
Binary file added assets/202002231353.jfif
Binary file not shown.
Binary file added assets/202002231404.jfif
Binary file not shown.
Binary file added assets/202002231406.jfif
Binary file not shown.
49 changes: 47 additions & 2 deletions 编程语言/JAVA/JAVA源码解析/队列.md
@@ -1,5 +1,15 @@
# 队列源码解析

## 设计思想

![202002231406](/assets/202002231406.jfif)

- 数据结构
- 入队出队方式
- 通信机制
- 强关联:take与put要互相等待
- 无关联:只要队列容器不满,生产者就能放成功,生产者就可以直接返回,和有无消费者一点关系都没有,生产者和消费者完全解耦

## LinkedBlockingQueue

### 类结构层次
Expand Down Expand Up @@ -112,6 +122,11 @@ public E take() throws InterruptedException {
}
```


### 使用场景

适合对生产的数据大小不定(时高时低),数据量较大的场景

## SynchronousQueue

其本身是没有容量大小,比如我放一个数据到队列中,我是不能够立马返回的,我必须等待别人把我放进去的数据消费掉了,才能够返回
Expand Down Expand Up @@ -140,7 +155,7 @@ static final class TransferQueue<E> extends Transferer<E> {}

反之,如果传进来的e不是null,并且有一个take线程阻塞,则将e通过节点传给take线程

### DelayQueue
## DelayQueue

DelayQueue 中的元素必须是 Delayed 的子类,Delayed 是表达延迟能力的关键接口,其继承了 Comparable 接口,并定义了还剩多久过期的方法

Expand Down Expand Up @@ -220,6 +235,10 @@ public E take() throws InterruptedException {
}
```

### 使用场景

用于任务不想立马执行,想等待一段时间才执行的场景

## ArrayBlockingQueue

这个队列一个重要的特点是有界的阻塞数组,容量一旦创建,后续大小无法修改
Expand Down Expand Up @@ -342,6 +361,10 @@ void removeAt(final int removeIndex) {
}
```

### 使用场景

一般用于生产数据固定的场景

## 问题

### 对队列的理解
Expand All @@ -368,4 +391,26 @@ SynchronousQueue 同步队列,当线程 put 时,必须有对应线程把数

两个方法都是无限(永远、没有超时时间的意思)阻塞的方法

使用 offer 和 poll 方法来代替两者,可以设置超时阻塞时间
使用 offer 和 poll 方法来代替两者,可以设置超时阻塞时间

## 队列在JDK中的其他运用

### 线程池

![202002231353](/assets/202002231353.jfif)

```java
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
```

> 参考JAVA编程规范中的不要用Executors创建线程池,而要手动创建
###

同步队列

![202002231404](/assets/202002231404.jfif)

0 comments on commit bd4d46a

Please sign in to comment.