// 定义一个 ThreadLocal 变量
public class ThreadLocalExample {
// 创建一个 ThreadLocal 变量,每个线程都有自己独立的副本
private static ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0);
public static void main(String[] args) throws InterruptedException {
// 创建多个线程并启动它们
Runnable task = () -> {
// 获取当前线程的 ThreadLocal 值
Integer value = threadLocalValue.get();
System.out.println("Thread " + Thread.currentThread().getName() + " initial value: " + value);
// 修改当前线程的 ThreadLocal 值
threadLocalValue.set(value + 1);
System.out.println("Thread " + Thread.currentThread().getName() + " updated value: " + threadLocalValue.get());
};
// 创建并启动多个线程
Thread t1 = new Thread(task, "t1");
Thread t2 = new Thread(task, "t2");
t1.start();
t2.start();
t1.join();
t2.join();
}
}
ThreadLocal 的定义:
ThreadLocal<Integer> threadLocalValue = ThreadLocal.withInitial(() -> 0);
创建了一个 ThreadLocal
变量,并设置了初始值为 0
。每个线程都会拥有自己独立的副本。线程任务:
Runnable task
定义了一个线程任务,在这个任务中,每个线程会获取自己的 ThreadLocal
变量的值,并将其打印出来。ThreadLocal
变量的值,并再次打印出来。线程创建与启动:
new Thread(task, "t1")
和 new Thread(task, "t2")
分别创建了两个线程 t1
和 t2
,并启动它们。join()
方法确保主线程等待子线程执行完毕后再继续执行。通过这种方式,ThreadLocal
可以确保每个线程都有自己独立的变量副本,避免了多线程环境下的数据竞争问题。
上一篇:java截取字符串方法
下一篇:java replace
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站