【问题标题】:Accessing ThreadLocal values from a method which a thread has invoked?从线程调用的方法访问 ThreadLocal 值?
【发布时间】:2020-02-17 16:56:47
【问题描述】:

我很少使用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

【问题讨论】:

  • 您将Threadlocal 的值保存到静态变量Thread1.t1 中。这个变量可以从任何地方访问,不需要传递引用。
  • @AlexeiKaigorodov:如果我像“普通”变量一样创建它,那么无论线程正在执行哪个代码,线程都没有任何方法可以访问吗?我需要钩子才能检索值?
  • 随便找个代码例子,严格按照。不要发明自己的自行车。仅当您无法复制已发布的示例时,请在此处提问。
  • 其实Thread1.t1的值就是那个钩子。当你使用getset 访问它时,它会考虑当前线程。

标签: java multithreading thread-local


【解决方案1】:

只要您不在 display 方法中的不同线程中执行代码,您可以将线程本地的值而不是线程本地的值传递给 display 方法。以下代码将导致相同的结果

@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);
}

}

【讨论】:

    猜你喜欢
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多