企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
> ### `ThreadLocal` * `ThreadLocal`,即线程变量。在`ThreadLocal`类中有一个`static`声明的`Map<ThreadID,Object>`,用于存储每一个线程的变量副本构,`key`为线程`id`,`value`为自己定义的任意数据类型并绑定到对应的`key`的线程上。 * 示例代码 ``` public class ThreadLocalDemo { //类型为map的ThreadLocal public static final ThreadLocal<HashMap<Integer, Long>> TIME_THREADLOCAL = new ThreadLocal<HashMap<Integer, Long>>() { //重写initialValue方法,初始化 protected HashMap<Integer, Long> initialValue() { return new HashMap<Integer, Long>(); } }; // TIME_THREADLOCAL 针对每个线程 创建了一个副本 public static class ThreadDemo implements Runnable{ int index; public ThreadDemo(int index){ this.index = index; } public static final void begin() { HashMap<Integer, Long> map = new HashMap<Integer, Long>(); map.put(0, System.currentTimeMillis()); //set TIME_THREADLOCAL.set(map); } public static final long end() { //get return System.currentTimeMillis() - TIME_THREADLOCAL.get().get(0); } public void run(){ ThreadDemo.begin(); try { TimeUnit.SECONDS.sleep(this.index); // TimeUnit.SECONDS.sleep((int)(Math.random()*10)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Thread: " + Thread.currentThread().getName() + " | Cost: " + ThreadDemo.end() + " mills"); } } public static void main(String[] args) throws Exception { for (int i = 0; i < 10; i++) { Thread thread = new Thread(new ThreadDemo(i), String.valueOf(i)); thread.start(); } } } ```