java - 从线程调用的方法访问 ThreadLocal 值?
问题描述
我用ThreadLocal
的很少,但是出于工作原因我需要了解它。我确实对此进行了搜索,并了解了这个概念。
我在下面做了示例:
ThreadLocalMain.java -> 主驱动程序
package com.example.threads.threadlocal;
public class ThreadLocalMain {
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1("First");
Thread1 t2 = new Thread1("Second");
Thread1 t3 = new Thread1("Third");
t1.start();
t2.start();
t3.start();
}
}
Thread1.java -> 使用哪个ThreadLocal
package com.example.threads.threadlocal;
import com.example.threads.threadlocal.utils.Util1;
public class Thread1 extends Thread {
private static Integer unique_id = 0;
@SuppressWarnings("rawtypes")
private static ThreadLocal tl = new ThreadLocal() {
@Override
public Integer initialValue() {
return (++unique_id);
}
};
public Thread1(String name) {
super(name);
}
@Override
public void run() {
System.out.println("Current thread is --> " + Thread.currentThread().getName() + " with thread local value as --> " + tl.get());
Util1 u1 = new Util1();
u1.display(tl);
}
Util.java --> 在这个我想检查 Thread 的 ThreadLocal 值
package com.example.threads.threadlocal.utils;
public class Util1 {
public void display(ThreadLocal tl) {
System.out.println("Inside Util1#display() method, executed by " + Thread.currentThread().getName()
+ " my thread local value is --> " + tl.get());
}
}
我有主驱动程序,它创建 3 个线程,并且在线程类中有ThreadLocal
保存当前线程的值。
我的问题是我们如何打印当前线程的 ThreadLocal 值,该线程调用了某个对象的方法。在这种情况下,对象是Util
。我可以通过将实例传递给方法来做到这ThreadLocal
一点Util's
display()
。
所以我的问题:
是否可以在不传递ThreadLocal
对方法的引用的情况下在方法中打印 ThreadLocal 的值?这完全可行吗?我的方法是不是它打算使用的方式ThreadLocal
。
解决方案
只要您不在显示方法中的不同线程中执行代码,您可以将线程本地的值而不是线程本地的值传递给显示方法。以下代码将导致相同的结果
@Override
public void run() {
System.out.println("Current thread is --> " + Thread.currentThread().getName() + " with thread local value as --> " + tl.get());
Util u1 = new Util();
u1.display(tl.get());
}
public class Util {
public void display(Object value) {
System.out.println("Inside Util1#display() method, executed by " + Thread.currentThread().getName()
+ " my thread local value is --> " + value);
}
}
推荐阅读
- excel - VBA Excel:将范围内容放入数组时出现运行时错误13 - 长单元格内容
- java - 上传大文件时OOM
- azure - 如何添加/使用构建标签?
- c# - 逐步调试时覆盖 ToString() 无法正常工作
- ms-access - 如何将电子邮件导入 ms access 并将其附件保存到可以通过 access 引用的网络驱动器
- c++ - substr 会改变 find 函数开始搜索的位置吗?
- java - Jackson:将 JSON-Node-Source 存储在反序列化对象中
- tfs - Azure DevOps Server 2019:覆盖的行数而不是百分比
- python - 动态改变fields.selection选项
- python - 当条件不满足时,无法让我的脚本继续尝试几次