java ThreadLocal 的使用



java ThreadLocal 的使用。/**
* 演示 ThreadLocal 的使用
*/
public class ThreadLocalTest {
//
ThreadLocal 是一个泛型容器
private static ThreadLocal<String> threadName =
new ThreadLocal<String>();

// 将对象放入 ThreadLocal
public
static void setThreadName(String name) {
threadName.set(name);

}

// 从 ThreadLocal 中读取内容
public static String getThreadName()
{
return threadName.get();
}

// 程序入口
public
static void main(String[] args) throws Exception {
// 启动 5
个线程。它们隔一段时间输出一行文字。
// 文字的内容是从同一个静态方法中取出来的,但
// 这 5
个线程输出的内容各不相同。这是因为使用
// 了 ThreadLocal。
for (int i = 0; i
< 5; i++) {
new TestThread(i).start();

Thread.sleep(500);
}
}

// 测试线程
private
static class TestThread extends Thread {
private int index;


// 注意这个方法的执行仍然是在主线程中
public TestThread(int index) {

this.index = index;
}

// 这里才是在新的线程中执行

@Override
public void run() {

ThreadLocalTest.setThreadName(“Thread ” + index);
while (true)
{
System.out.println(ThreadLocalTest.getThreadName() + ”
ticks.”);
try {
sleep(3000);

} catch (InterruptedException e) {
// nothing to
do
}
}
}
}
}