java 多线程 :ThreadLocal 共享变量多线程不同值方案;InheritableThreadLocal变量子线程中自定义值,孙线程可继承
ThreadLocal类的使用
变量值的共享可以使用public static变量的形式,所有的线程都是用同一个public static变量。如果想实现每一个线程都有自己的值。该变量可通过ThreadLocal实现定义:ThreadLocal<T> name = new ThreadLocal<>();
用法:
- 用法1、变量在线程外定义,在线程执行体内.set()赋值。
- 用法2、变量在定义时设置自动赋值的方法。在对应线程中运行时则自动赋值。
ThreadLocal<T> name = new ThreadLocal<>(){
@Override
protected String initialValue() {
return <T> t;
}
};
取值:.get()
用法1示例:
import javax.management.relation.RelationNotFoundException; /** * @ClassName ThreadLocalExample * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/24. */ public class ThreadLocalExample { private static ThreadLocal<String> name = new ThreadLocal<>(); public static void main(String[] args) { Runnable r = () -> { String threadname = Thread.currentThread().getName(); /** * 线程运行时赋值 */ name.set(threadname); System.out.println(name.get()); //不同的子线程对应子线程名,本例A\B\C }; Thread thread = new Thread(r,"A"); Thread thread2 = new Thread(r,"B"); Thread thread1 = new Thread(r,"C"); thread.start(); thread1.start(); thread2.start(); System.out.println(name.get()); //主线程中没有赋值默认为null } }
用法二示例:
/** * @ClassName ThreadLocalInitialValue * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/24. */ public class ThreadLocalInitialValue { /** * 定义ThreadLocal变量线程中运行自动初始化值 */ private static ThreadLocal<String> name = new ThreadLocal<>(){ @Override protected String initialValue() { return Thread.currentThread().getName(); } }; public static void main(String[] args) { Runnable r = new Runnable() { @Override public void run() { System.out.println("我是" + name.get()); } }; Thread zhangsan = new Thread(r,"张三"); Thread lisi = new Thread(r,"李四"); zhangsan.start(); lisi.start(); System.out.println("main线程中,我是" + name.get()); } }
InheritableThreadLocal子线程中自定义值,孙线程可继承
import java.io.Reader; import java.sql.SQLOutput; /** * @ClassName ThreadLocalSubThread * @projectName: object1 * @author: Zhangmingda * @description: XXX * date: 2021/4/24. */ public class ThreadLocalSubThread { /** * 定义变量时,设置自动赋值方法 */ private static ThreadLocal<String> name = new InheritableThreadLocal<>(){ @Override protected String initialValue() { return Thread.currentThread().getName(); } }; public static void main(String[] args) { Runnable r = () -> { System.out.println("我是子线程:"+ name.get());//我是子线程:child Thread t = new Thread(){ @Override public void run() { System.out.println("我是孙线程,获取子线程变量值:"+ name.get());//也是child } }; t.start(); }; Thread thread = new Thread(r,"child"); thread.start(); name.set("主线程"); //主线程中手动赋值 System.out.println("main线程中 name:" + name.get()); //"主线程" } }
posted on 2021-04-24 20:15 zhangmingda 阅读(302) 评论(0) 编辑 收藏 举报