【发布时间】:2011-07-07 23:56:29
【问题描述】:
鉴于一个 ThreadLocal 变量为不同的线程保存不同的值,是否可以从另一个线程访问一个 ThreadLocal 变量的值?
即在下面的示例代码中,是否可以在 t1 中从 t2 读取 TLocWrapper.tlint 的值?
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 () {}
}
【问题讨论】:
-
具有适当读/写锁定的常规变量用于在线程之间共享数据。 ThreadLocal 是专门在您/不/想要在线程之间共享数据的情况下创建的。这让我相信这要么是一个纯粹的假设性问题,要么你正试图用 ThreadLocal 做一些事情,它是专门不打算用于的。
-
@Cthulhu:是的,我正在尝试用 ThreadLocal 做一些“邪恶”的事情——但我的意图是好的 :)。我只是想解决一个问题。
-
顺便说一句:你必须让 kill 字段易变,这是一个非常微妙的错误。
标签: java multithreading