ThreadLocal类
变量值的共享可以通过使用public static变量的形式。如果想每个线程都有自己的共享变量,可以通过JDK提供的ThreadLocal来实现。
类 ThreadLocal 主要解决的就是每个线程绑定自己的值,可以将 ThreadLocal 类比喻成全局存放数据的盒子,盒子中可以存放每个线程的私有变量。
示例:
public class Test { public static void main(String[] args) { try { for (int i = 0; i < 5; i++) { System.out.println(" 在 Main 线程中取值 = " + ThreadLocalHolder.getInstance().get()); Thread.sleep(500); } Thread.sleep(2500); ThreadA a = new ThreadA(); a.start(); } catch (InterruptedException e) { e.printStackTrace(); } } static class ThreadA extends Thread { @Override public void run() { try { for (int i = 0; i < 5; i++) { System.out.println("在 ThreadA 线程中取值 = " + ThreadLocalHolder.getInstance().get()); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } static class ThreadLocalHolder { private ThreadLocalHolder() { } public static ThreadLocal getInstance() { return ThreadLocalHolder.Holder.INSTANCE; } private static class Holder { static final ThreadLocalHolder.MyThreadLocal INSTANCE = new ThreadLocalHolder.MyThreadLocal(); } /** * 集成 ThreadLocal,给每个线程的共享变量一个初始值 */ private static class MyThreadLocal extends ThreadLocal { @Override protected Object initialValue() { return System.currentTimeMillis(); } } } }
运行结果如图:
类InheritableThreaddLocal 的使用
使用类 InheritableThreadLocal 可以在子线程中取得父线程继承下来的值。
示例:
public class Test { public static void main(String[] args) { try { for (int i = 0; i < 5; i++) { System.out.println(" 在 Main 线程中取值 = " + ThreadLocalHolder.getInstance().get()); Thread.sleep(500); } Thread.sleep(2500); ThreadA a = new ThreadA(); a.start(); } catch (InterruptedException e) { e.printStackTrace(); } } static class ThreadA extends Thread { @Override public void run() { try { for (int i = 0; i < 5; i++) { System.out.println("在 ThreadA 线程中取值 = " + ThreadLocalHolder.getInstance().get()); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } } static class ThreadLocalHolder { private ThreadLocalHolder() { } public static InheritableThreadLocal getInstance() { return ThreadLocalHolder.Holder.INSTANCE; } private static class Holder { static final ThreadLocalHolder.MyInheritableThreadLocal INSTANCE = new ThreadLocalHolder.MyInheritableThreadLocal(); } /** * 集成 InheritableThreadLocal,给每个线程的共享变量一个初始值 */ private static class MyInheritableThreadLocal extends InheritableThreadLocal { @Override protected Object initialValue() { return System.currentTimeMillis(); } } } }
运行结果如下:
原文地址:https://www.cnblogs.com/lkc9/p/12560592.html
时间: 2024-10-12 20:50:12