本文共 2196 字,大约阅读时间需要 7 分钟。
变量值的共享可以使用public static变量的形式,所有的线程都使用同一个public static变量。如果想实现每一个线程
都有自己的共享变量。JDK中提供的类ThreadLocal正是为了解决这样的问题。
类ThreadLocal主要解决的就是每个线程绑定自己的值。
1. 方法get()与null
public class Run { public static ThreadLocal t1=new ThreadLocal(); public static void main(String[] args){ if(t1.get()==null){ System.out.println("从未放过值"); t1.set("我的值"); } System.out.println(t1.get()); System.out.println(t1.get()); }}效果:
从未放过值
我的值 我的值2.验证线程变量的隔离性
看例子
public class ThreadA extends Thread { @Override public void run() { try { for (int i = 0; i < 100; i++) { Tools.t1.set("ThreadA" + (i + 1)); System.out.println("ThreadA get Value " + Tools.t1.get()); Thread.sleep(200); } } catch (InterruptedException e) { e.printStackTrace(); } }}
public class ThreadB extends Thread{ @Override public void run() { try{ for(int i=0;i<100;i++) { Tools.t1.set("ThreadB" + (i + 1)); System.out.println("ThreadB get Value=" + Tools.t1.get()); Thread.sleep(200); } }catch (InterruptedException e){ e.printStackTrace(); } }}
public class Run { public static void main(String[] args1){ try{ ThreadA a=new ThreadA(); ThreadB b=new ThreadB(); a.start(); b.start(); for(int i=0;i<100;i++){ Tools.t1.set("Main"+(i+1)); System.out.println("Main get Value="+Tools.t1.get()); Thread.sleep(200); } }catch (InterruptedException e){ e.printStackTrace(); } }}
3.解决get()返回null问题
通过给定初始化值
public class ThreadLocalExt extends ThreadLocal{ @Override protected Object initialValue() { return "我是默认值 第一次get不再为null"; }}
public class Run { public static ThreadLocalExt t1=new ThreadLocalExt(); public static void main(String[] args){ if(t1.get()==null){ System.out.println("从未放过值"); t1.set("我的值"); } System.out.println(t1.get()); System.out.println(t1.get()); }}
转载地址:http://dmjqi.baihongyu.com/