首页 > 解决方案 > 从线程调用的方法访问 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

标签: javamultithreadingthread-local

解决方案


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

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

}


推荐阅读