java多线程之ThreadLocal
package com.wz.thread.threadLocal;
import java.util.Date;
/**
* ThreadLocal解决每个线程绑定自己的值
* @author Administrator
*
*/
public class ThreadLocalExt extends ThreadLocal{
@Override
protected Object initialValue() {
return new Date().getTime();
}
}
package com.wz.thread.threadLocal;
public class Tools {
public static ThreadLocalExt t1 = new ThreadLocalExt();
}
package com.wz.thread.threadLocal;
public class ThreadA extends Thread{
@Override
public void run() {
super.run();
try {
for(int i = 0; i < 10; i++) {
System.out.println("在ThreadA线程中取值=" + Tools.t1.get());
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.wz.thread.threadLocal;
public class Run {
public static void main(String[] args) {
try {
for(int i = 0; i < 10; i++) {
System.out.println(" 在Main线程中取值=" + Tools.t1.get());
Thread.sleep(100);
}
Thread.sleep(5000);
ThreadA a = new ThreadA();
a.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}