InheritableThreadLocal 与 ThreadLocal

package com.verser.weixin.test;

public class Test {
	static InheritableThreadLocal<Object> ITL = new InheritableThreadLocal<Object>(){
		protected Object initialValue() {
			return new StringBuffer("hello ");
		};
	};
	
	static ThreadLocal<Object> TL = new ThreadLocal<Object>(){
		protected Object initialValue() {
			return new StringBuffer("HELLO ");
		};		
	};
	
	public static void main(String[] args) throws Exception {
		
		System.out.println("Thread-t " + " , " + ITL.get() + " , " + TL.get());		
		Thread t_1 = new Thread(new Runnable() {
			@Override
			public void run() {		
				System.out.println("Thread-t_1 " + " , " + ITL.get() + " , " + TL.get());
				
				((StringBuffer)ITL.get()).append("wonderful ");
				((StringBuffer)TL.get()).append("WONDERFUL ");
				
				Thread t_1_1 = new Thread(new Runnable() {
					@Override
					public void run() {
						System.out.println("Thread-t_1_1 "  + " , " + ITL.get() + " , " + TL.get());
						((StringBuffer)ITL.get()).append("world");
						((StringBuffer)TL.get()).append("WORLD");
						System.out.println("Thread-t_1_1 " + " , " + ITL.get() + " , " + TL.get());
					}
				});
				t_1_1.start();
				try {
					t_1_1.join();
					System.out.println("Thread-t_1 " + " , " + ITL.get() + " , " + TL.get());
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		t_1.start();
		t_1.join();
		System.out.println("Thread-t " + " , " + ITL.get() + " , " + TL.get());
		
	}
}

 

Thread-t  , hello  , HELLO 
Thread-t_1  , hello  , HELLO 
Thread-t_1_1  , hello wonderful  , HELLO 
Thread-t_1_1  , hello wonderful world , HELLO WORLD
Thread-t_1  , hello wonderful world , HELLO WONDERFUL 
Thread-t  , hello wonderful world , HELLO 

 

你可能感兴趣的:(threadLocal)