直接看代码示例
package com.book.java7.concurrency;
import java.time.LocalDate;
import java.util.concurrent.TimeUnit;
/** *//**
* {@link InheritableThreadLocal}示例
*
* <pre>
* public class InheritableThreadLocal<T> extends ThreadLocal<T> {
* protected T childValue(T parentValue) {
* return parentValue;
* }
* </pre>
*
* <pre>
* childValue方法是在子线程初始化时调用的,可(Thread.dump).将【子线程-childValue】和date绑定.
* 子线程调用date.get时, 会取到子线程初始化时放到ThreadLocalMap的值.
* </pre>
*
* <p>
* landon认为其实是用线程局部变量这个类更多的原因可能在于为了隐藏线程内部的一些实现细节,使用户外部调用更简单,完全不必理会线程内部的一些东西!
*
* @author landon
*
*/
public class InheritableThreadLocalExample {
private static class Task implements Runnable {
// InheritableThreadLocal局部变量
private static InheritableThreadLocal<LocalDate> date = new InheritableThreadLocal<LocalDate>() {
// 初始化
protected LocalDate initialValue() {
return LocalDate.now();
}
// 首先输出继承的值.然后改变子线程局部变量的值(加了一天)
protected LocalDate childValue(LocalDate parentValue) {
// Thread.dumpStack();
System.out.println(String.format("call childValue Thread:%s,parentValue:%s", Thread.currentThread()
.getName(), parentValue));
return parentValue.plusDays(1);
}
};
@Override
public void run() {
System.out.println(String.format("%s:task begin.date:%s", Thread.currentThread().getName(), date.get()));
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 创建一个子线程
// 从输出可以看到:此时输出的是childValue改变后的值
Thread subThread = new Thread(Thread.currentThread().getName() + "-sub") {
@Override
public void run() {
System.out.println(String.format("%s:task execute.date:%s", Thread.currentThread().getName(),
date.get()));
}
};
subThread.start();
System.out.println(String.format("%s:task end.date:%s", Thread.currentThread().getName(), date.get()));
}
}
public static void main(String[] args) throws Exception {
Task task = new Task();
for (int i = 0; i < 3; i++) {
Thread t = new Thread(task, "Main-Sub-" + i);
t.start();
Thread.sleep(1000);
}
}
}
posted on 2014-11-25 16:22
landon 阅读(6142)
评论(0) 编辑 收藏 所属分类:
Program