使用threadlocal和不使用threadlocal的代码演示:java
时间: 2024-06-17 17:00:45 浏览: 16
使用ThreadLocal的代码演示:
```
public class ThreadLocalExample {
public static void main(String[] args) throws InterruptedException {
ThreadLocal<String> threadLocal = new ThreadLocal<>();
// 创建线程1并启动
Thread thread1 = new Thread(() -> {
threadLocal.set("Thread1 Local Value");
System.out.println("Thread1 local value: " + threadLocal.get());
});
thread1.start();
thread1.join();
// 创建线程2并启动
Thread thread2 = new Thread(() -> {
threadLocal.set("Thread2 Local Value");
System.out.println("Thread2 local value: " + threadLocal.get());
});
thread2.start();
thread2.join();
}
}
```
运行结果:
```
Thread1 local value: Thread1 Local Value
Thread2 local value: Thread2 Local Value
```
不使用ThreadLocal的代码演示:
```
public class NonThreadLocalExample {
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static void main(String[] args) throws InterruptedException {
NonThreadLocalExample example = new NonThreadLocalExample();
// 创建线程1并启动
Thread thread1 = new Thread(() -> {
example.setValue("Thread1 Local Value");
System.out.println("Thread1 local value: " + example.getValue());
});
thread1.start();
thread1.join();
// 创建线程2并启动
Thread thread2 = new Thread(() -> {
example.setValue("Thread2 Local Value");
System.out.println("Thread2 local value: " + example.getValue());
});
thread2.start();
thread2.join();
}
}
```
运行结果:
```
Thread1 local value: Thread1 Local Value
Thread2 local value: Thread2 Local Value
```
可以看出,使用ThreadLocal时每个线程拥有自己独立的变量副本,不同线程之间的变量值互不干扰。而不使用ThreadLocal时,多个线程共享同一个变量,会发生竞争条件,导致结果不确定。
相关推荐
![](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)
![](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)