Java多线程-ThreadLocal和InheritableThreadLocal的使用
Posted Alan Lau
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java多线程-ThreadLocal和InheritableThreadLocal的使用相关的知识,希望对你有一定的参考价值。
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(); } } } }
运行结果如下:
以上是关于Java多线程-ThreadLocal和InheritableThreadLocal的使用的主要内容,如果未能解决你的问题,请参考以下文章