码迷,mamicode.com
首页 > 编程语言 > 详细

threadLocal测试用例,说明线程本地私有

时间:2020-04-17 00:11:52      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:img   false   cep   package   pre   void   demo   exception   一个   

package thread.test;

public class ThreadLocalDemo {
	/**
	 * ThreadLocal变量,每个线程都有一个副本,互不干扰
	 */
	private static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<>();

	public static void main(String[] args) throws Exception {
		new ThreadLocalDemo().threadLocalTest();
	}

	public void threadLocalTest() throws Exception {
		// 主线程设置值
		THREAD_LOCAL.set("1");
		String v = THREAD_LOCAL.get();
		System.out.println("Thread-0线程执行之前," + Thread.currentThread().getName() + "线程取到的值:" + v);

		new Thread(new Runnable() {
			@Override
			public void run() {
				String v = THREAD_LOCAL.get();
				System.out.println(Thread.currentThread().getName() + "线程取到的值:" + v);
				// 设置 threadLocal(这也说明了每个线程都有一个threadLocal)
				THREAD_LOCAL.set("2");
				v = THREAD_LOCAL.get();
				System.out.println("重新设置之后," + Thread.currentThread().getName() + "线程取到的值为:" + v);
				System.out.println(Thread.currentThread().getName() + "线程执行结束");
			}
		}).start();
		// 等待所有线程执行结束
		Thread.sleep(3000L);
		// main线程重新取,取到的是自己线程私有的本地线程私有变量
		v = THREAD_LOCAL.get();
		System.out.println("Thread-0线程执行之后," + Thread.currentThread().getName() + "线程取到的值:" + v);
	}
}

  技术图片

 

threadLocal测试用例,说明线程本地私有

标签:img   false   cep   package   pre   void   demo   exception   一个   

原文地址:https://www.cnblogs.com/dashenaichicha/p/12716766.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!