ThreadLocal使用
- 实现线程之间变量隔离,不同线程存取不同的值。使用方法 例1
- 默认情况下初始值为null 可以通过继承类重写initialValue方法进行修改初始值
例1:
import java.util.Date;
class ThreadLocalExt extends ThreadLocal {
@Override
protected Object initialValue() {
return "设置初始化值";
}
}
class Tools {
public static ThreadLocalExt threadLocalExt = new ThreadLocalExt();
}
class ThreadA08 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (Tools.threadLocalExt.get() == null) {
Tools.threadLocalExt.set(new Date());
}
System.out.println(ThreadA.currentThread().getName() + "---" + Tools.threadLocalExt.get());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class StudyThreads08ThreadLocal的使用 {
public static void main(String[] args) {
ThreadA08 threadA08 = new ThreadA08();
threadA08.start();
for (int i = 0; i < 10; i++) {
if (Tools.threadLocalExt.get() == null) {
Tools.threadLocalExt.set(new Date());
}
Tools.threadLocalExt.set(new Date());
System.out.println(ThreadA.currentThread().getName() + "---" + Tools.threadLocalExt.get());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
InheritableThreadLocal 可以针对子线程和父线程返回不同的值
package com.chapter03;
import java.util.Date;
//class ThreadLocalExt extends ThreadLocal {
// @Override
// protected Object initialValue() {
// return "设置初始化值";
// }
//}
class Tools {
public static ThreadLocalExt threadLocalExt = new ThreadLocalExt();
}
class ThreadA08 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (Tools.threadLocalExt.get() == null) {
Tools.threadLocalExt.set(new Date());
}
System.out.println(ThreadA.currentThread().getName() + "---" + Tools.threadLocalExt.get());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class StudyThreads08ThreadLocal的使用 {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (Tools.threadLocalExt.get() == null) {
Tools.threadLocalExt.set(new Date());
}
System.out.println(ThreadA.currentThread().getName() + "---" + Tools.threadLocalExt.get());
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
ThreadA08 threadA08 = new ThreadA08();
threadA08.start();
}
}
class ThreadLocalExt extends InheritableThreadLocal {
@Override
protected Object initialValue() {
return new Date();
}
@Override
protected Object childValue(Object parentValue) {
return parentValue + "针对子线程添加不同的内容";
}
}