当前位置: 移动技术网 > 网络运营>服务器>Linux > 多线程学习之-ThreadLocal

多线程学习之-ThreadLocal

2020年07月29日  | 移动技术网网络运营  | 我要评论

一、ThreadLocal使用

        在并发的环境中,每一个线程会将ThreadLocal的实例指向的内容拷贝一份到自己的工作副本中,在有很多线程使用一个相同的对象并且初始化的值是相同的时候,那么使用ThreadLocal是比较合适的。

 

二、怎么给ThreadLocal初始化?

     通过重写initialValue()方法,并返回一个泛型值,就可以初始化ThreadLocal:

package com.example.thread;

/**
 * ThreadLocal使用
 * @author FHQFIN06
 *  初始化threadLocal
 */

public class Demo05 {


	private static ThreadLocal<String> threadLocal=new ThreadLocal<String>(){
		@Override
		protected String initialValue() {
			// TODO Auto-generated method stub
			return "重写initialValue初始化值!";
		}
	};


	public static void main(String[] args) {
		//threadLocal.set("初始化一个值!");
		System.out.println(threadLocal.get());
		threadLocal.set("使用set设置一个值!");
		System.out.println(threadLocal.get());
		//打印结果为: 使用set设置一个值! 
	}
}

      ThreadLocal每个线程都有一份内容的拷贝,下面打印的结果为:

    

package com.example.thread;

import com.example.contructor.main;

/**
 * ThreadLocal 的使用
 * @author FHQFIN06
 *
 */

public class Demo06 {



	public static class MyDemo implements Runnable{
		private  static ThreadLocal<String> threadLocal=new ThreadLocal<String>();
		@Override
		public void run() {
			int v=(int)(Math.random()*100);
			System.out.println(Thread.currentThread().getId()+":"+v);
			threadLocal.set(v+"");
			System.out.println(Thread.currentThread().getId()+":"+threadLocal.get());
		}
	}


	public static void main(String[] args) throws InterruptedException {
		Thread thread1=new Thread(new MyDemo());
		Thread thread2=new Thread(new MyDemo());
		thread1.start();
		thread2.start();
		thread2.join();
		new MyDemo();
		//该线程为主线程,因此打印出来的threadLocal的内容为Null
		System.out.println(MyDemo.threadLocal.get());
	}

}

打印结果为:

  10:81
11:97
10:81
11:97
null

由于每个线程的副本是独立的,主线程没有对threadLocal进行set,因此获取到的值是null。

 

三、 InheritableThreadLocal

       InheritableThreadLocal 能够使子线程访问到主线程的数据, 即InheritableThreadLocal能允许一个线程创建的子线程访问父线程的值。

package com.example.thread;

public class Demo07 {
	
	private static InheritableThreadLocal<String> inLocal=new InheritableThreadLocal<String>();
	public static void main(String[] args) {
		 inLocal.set("主线程设置值");
		 Thread thread1=new Thread(new Demo07().new Son()); 
		 thread1.start();
	}
	
	
	public class Son implements Runnable{

		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()+"="+inLocal.get());
		}
		
	}

}

        如下打印结果为:

         Thread-0=主线程设置值

         由此发现子线程获取到了主线程set的值! 

本文地址:https://blog.csdn.net/qq_33036061/article/details/107613243

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网