Files
rikako-note/java se/juc.md
2023-10-30 21:21:45 +08:00

30 lines
1.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# juc
## ThreadLocal
通过ThreadLocal api可以存储对象并且存储的对象只有指定线程才能够访问。
### 示例
```java
// 声明一个ThreadLocal对象其中存储的Integer值和特定线程绑定
ThreadLocal<Integer> threadLocalVlaue = new ThreadLocal<>();
// 再特定线程中调用get/set方法可以对与该线程绑定
// 的integer值进行获取或设置
threadLocalValue.set(1);
Integer result = threadLocalValue.get();
```
ThreadLocal类似于一个map其中key为线程value为与线程绑定的值再特定线程中调用
### api
#### withInitial
可以通过`ThreadLocal.withInitial`方法来构造一个带初始值的threadLocal对象该静态方法接收一个supplier对象。
```java
ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);
```
如果一个ThreadLocal对象指定了withInitial方法那么当该ThreadLocal对象get为空时会调用withInitial并用该方法的返回值来初始化该threadLocal对象。
#### remove
如果要移除ThreadLocal中的对象可以调用`remove`方法
```java
threadLocal.remove();
```