跨不同线程的ThreadLocal值访问 [英] ThreadLocal value access across different threads

查看:107
本文介绍了跨不同线程的ThreadLocal值访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于ThreadLocal变量为不同的线程保存不同的值,是否可以从另一个线程访问一个ThreadLocal变量的值?

Given that a ThreadLocal variable holds different values for different threads, is it possible to access the value of one ThreadLocal variable from another thread?

I.e。在下面的示例代码中,是否可以在 t1 中从 t2 中读取 TLocWrapper.tlint 的值?

I.e. in the example code below, is it possible in t1 to read the value of TLocWrapper.tlint from t2?

public class Example
{
  public static void main (String[] args)
  {
    Tex t1 = new Tex("t1"), t2 = new Tex("t2");
    new Thread(t1).start();
    try
    {
      Thread.sleep(100);
    }
    catch (InterruptedException e)
    {}
    new Thread(t2).start();
    try
    {
      Thread.sleep(1000);
    }
    catch (InterruptedException e)
    {}
    t1.kill = true;
    t2.kill = true;
  }

  private static class Tex implements Runnable
  {
    final String name;
    Tex (String name)
    {
      this.name = name;
    }
    public boolean kill = false;
    public void run ()
    {
      TLocWrapper.get().tlint.set(System.currentTimeMillis());
      while (!kill)
      {
        // read value of tlint from TLocWrapper
        System.out.println(name + ": " + TLocWrapper.get().tlint.get());
      }
    }
  }
}
class TLocWrapper
{
  public ThreadLocal<Long> tlint = new ThreadLocal<Long>();
  static final TLocWrapper self = new TLocWrapper();
  static TLocWrapper get ()
  {
    return self;
  }
  private TLocWrapper () {}
}


推荐答案

正如彼得所说,这是不可能的。如果你想要这种功能,那么概念上你真正想要的只是一个标准的 Map< Thread,Long> - 其中大多数操作将是使用 Thread.currentThread()的键完成,但如果您愿意,可以传入其他线程。

As Peter says, this isn't possible. If you want this sort of functionality, then conceptually what you really want is just a standard Map<Thread, Long> - where most operations will be done with a key of Thread.currentThread(), but you can pass in other threads if you wish.

但是,这可能不是一个好主意。首先,持有对垂死线程的引用会搞砸GC,所以你必须通过额外的箍来制作密钥类型 WeakReference< Thread> 。而且我不相信 Thread 无论如何都是一个很好的Map键。

However, this likely isn't a great idea. For one, holding a reference to moribund threads is going to mess up GC, so you'd have to go through the extra hoop of making the key type WeakReference<Thread> instead. And I'm not convinced that a Thread is a great Map key anyway.

所以一旦你超越了烤好的 ThreadLocal 的便利性,也许值得质疑是否使用 Thread 对象作为关键是最佳选择?为每个线程提供唯一ID(字符串或整数,如果它们还没有更有意义的自然键)可能会更好,只需使用这些来关闭地图。我意识到你的例子是人为的,但是你可以用 Map< String,Long> 并使用t1键来做同样的事情t2

So once you go beyond the convenience of the baked-in ThreadLocal, perhaps it's worth questioning whether using a Thread object as the key is the best option? It might be better to give each threads unique IDs (Strings or ints, if they don't already have natural keys that make more sense), and simply use these to key the map off. I realise your example is contrived, but you could do the same thing with a Map<String, Long> and using keys of "t1" and "t2".

由于<$ c $,它也可以说更清晰c> Map 表示您实际使用数据结构的方式; ThreadLocals更像是标量变量,具有一些访问控制魔法而不是集合,因此即使可以根据需要使用它们,对于查看代码的其他人来说也可能会更加混乱。

It would also arguably be clearer since a Map represents how you're actually using the data structure; ThreadLocals are more like scalar variables with a bit of access-control magic than a collection, so even if it were possible to use them as you want it would likely be more confusing for other people looking at your code.

这篇关于跨不同线程的ThreadLocal值访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆