Skip to content

Commit 5e331fa

Browse files
committed
A simple and good InheritableThreadLocal demo.
1 parent d71a770 commit 5e331fa

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
public class InheritableThreadLocalDemo{
2+
private static volatile InheritableThreadLocal<Integer> workerIndex = new InheritableThreadLocal<Integer>(){
3+
@Override
4+
protected Integer childValue(Integer parentValue){
5+
return parentValue + 5; // Default implementation return the parentValue.
6+
}
7+
};
8+
9+
public static void main(String[] args){
10+
Runnable parentRun = new Runnable(){
11+
@Override
12+
public void run(){
13+
workerIndex.set(new Integer(10));
14+
15+
Runnable childRun = new Runnable(){
16+
@Override
17+
public void run(){
18+
System.out.println(Thread.currentThread().getName() + "'s index is " + workerIndex.get());
19+
// This demonstrates the 'inheritable' property. Output 15.
20+
}
21+
};
22+
23+
Thread childThread = new Thread(childRun, "Child");
24+
childThread.start();
25+
26+
System.out.println(Thread.currentThread().getName() + "'s index is " + workerIndex.get()); // Output 10.
27+
}
28+
};
29+
30+
new Thread(parentRun, "Parent").start();
31+
}
32+
}

0 commit comments

Comments
 (0)