ThreadLocal类及应用技巧

来源:互联网 发布:乒乓球成品拍 知乎 编辑:程序博客网 时间:2024/05/16 16:55

一、基本类型变量共享

package com.test;import java.util.Random;/** *  * @author  * ThreadLocal:实现线程范围内单个变量共享,一个ThreadLocal对象代表一个变量,故其中只能放一个数据。 * ThreadLocal并不是一个Thread,而是Thread的局部变量,其本质也是通过内部定义的Map实现线程范围内的共享变量的。 */public class ThreadLocal_07 {    //定义静态变量ThreadLocalMap,key为当前线程,value为当前线程所拥有的变量    private  static  ThreadLocal<Integer> threadLocal=new ThreadLocal<Integer>();public static void main(String[] args) {for(int i=0;i<2;i++){//启动两个线程new Thread(new Runnable() {@Overridepublic void run() {int data=new Random().nextInt();//放入数据System.out.println(Thread.currentThread().getName()+" has putted data:"+data);//保存当前线程所拥有的信息threadLocal.set(data);new A().get();new B().get();}}).start();}}static class A{public void get(){System.out.println("A from "+Thread.currentThread().getName()+" get data:"+threadLocal.get());}}static class B{public void get(){System.out.println("B from "+Thread.currentThread().getName()+" get data:"+threadLocal.get());}}}
二、对象类型变量共享

package com.test;import java.util.Random;/** *  * @author  * ThreadLocal:实现线程范围内对象变量共享
   案例中将涉及了单例模式,并且也没有使用常规的对象共享方式,而是将ThreadLocal封装到了对象内部 */public class ThreadLocal_08 {  public static void main(String[] args) {for(int i=0;i<2;i++){//启动两个线程new Thread(new Runnable() {@Overridepublic void run() {int data=new Random().nextInt();ThreadObject.getInstance().setAge(data);ThreadObject.getInstance().setName("张三");new A().get();new B().get();}}).start();}}static class A{public void get(){//取得当前线程的对象实例ThreadObject threadObject=ThreadObject.getInstance();System.out.println("A from "+Thread.currentThread().getName()+" get data:"                  +"name-->"+threadObject.getName()+",age-->"+threadObject.getAge());}}static class B{public void get(){//取得当前线程的对象实例ThreadObject threadObject=ThreadObject.getInstance();System.out.println("B from "+Thread.currentThread().getName()+" get data:"                  +"name-->"+threadObject.getName()+",age-->"+threadObject.getAge());}}}/** *  * @author  * 单例模式:饥汉模式 */class ThreadObject{private String name;private Integer age;//将ThreadLocal封装在对象内部,每次获取该线程下对应的对象变量private static ThreadLocal<ThreadObject> map=new ThreadLocal<ThreadObject>();private ThreadObject(){}//单例模式/** * 多线程环境下,使用synchronized保证线程同步 * @return */public static synchronized ThreadObject getInstance(){ThreadObject threadObject=map.get();if(threadObject==null){threadObject=new ThreadObject();map.set(threadObject);}return threadObject;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}}



0 0
原创粉丝点击