类ThreadLocal
变量值的共享可以使用public static
变量的形式,所有线程都使用同一个public static
变量
如果想实现每一个线程都有自己的共享变量该如何解决?JDK
中提供了类ThreadLocal
正式为了解决这样的问题
实例
class Tools {
public static ThreadLocal<String> t = new ThreadLocal<>();
}
class A implements Runnable {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
Tools.t.set(Thread.currentThread().getName() + "-" + (i + 1));
System.out.println("A: " + Tools.t.get());
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class B implements Runnable {
@Override
public void run() {
try {
for (int i = 0; i < 100; i++) {
Tools.t.set(Thread.currentThread().getName() + "-" + (i + 1));
System.out.println("B: " + Tools.t.get());
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
Thread aThread = new Thread(new A());
Thread bThread = new Thread(new B());
aThread.start();
bThread.start();
for (int i = 0; i < 100; i++) {
Tools.t.set(Thread.currentThread().getName() + "-" + (i + 1));
System.out.println("MAIN: " + Tools.t.get());
Thread.sleep(200);
}
}
}
解决get返回null问题
继承ThreadLocal
,重写initialValue
方法
class ThreadLocalExt extends ThreadLocal {
@Override
protected Object initialValue() {
return "default value";
}
}
public class Run {
public static ThreadLicalExt t = new ThreadLocalExt();
public static void main(String[] args) {
if (Optional.ofNullable(t.get()).isEmpty()) {
System.out.println("no default value");
}
System.out.println(t.get());
}
}
网友评论