package com.xsl.thread;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadLocalTest {
public static void main(String[] args) {
threadLocalUsage2();
}
/**
* 用法1,每个线程有自己的拷贝
*/
private static void threadLocalUsage1(){
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 2L,
TimeUnit.MINUTES,new LinkedBlockingDeque<>());
ThreadLocal<SimpleDateFormat> threadLocal = ThreadLocal.withInitial(
() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
);
for (int i = 0; i < 1000; i++) {
int finalI = i;
SimpleDateFormat simpleDateFormat = threadLocal.get();
threadPoolExecutor.execute(() -> System.out.println(simpleDateFormat.format(new Date(finalI * 1000))));
}
}
/**
* 用法2:线程内共享
*/
private static void threadLocalUsage2(){
ContextHolder.getHolder().set("肖生亮");
func();
new Thread(ThreadLocalTest::fun1).start();
}
private static void func(){
String s = ContextHolder.getHolder().get();
System.out.println("func:" + s);
}
private static void fun1(){
String s = ContextHolder.getHolder().get();
System.out.println("func1:" + s);
ContextHolder.getHolder().set("刘文宇");
fun2();
}
private static void fun2(){
String s = ContextHolder.getHolder().get();
System.out.println("func2:" + s);
}
static class ContextHolder{
private static ThreadLocal<String> holder = new ThreadLocal<>();
public static ThreadLocal<String> getHolder() {
return holder;
}
public static void setHolder(ThreadLocal<String> holder) {
ContextHolder.holder = holder;
}
}
}
ThreadLocal两种用法示例
最新推荐文章于 2024-03-20 22:56:36 发布
本文介绍了Java中ThreadLocal的两种使用方法,展示了如何在线程中创建独立的变量副本以及如何在不同线程间共享数据。示例代码通过ThreadPoolExecutor执行任务,演示了ThreadLocal在并发环境下的应用。
摘要由CSDN通过智能技术生成