每天一例多线程[day11]-----ThreadLocal
发布日期:2021-06-30 13:45:02 浏览次数:2 分类:技术文章

本文共 879 字,大约阅读时间需要 2 分钟。

package com.jeff.base.conn010;public class ConnThreadLocal {	public static ThreadLocal
th = new ThreadLocal
(); public void setTh(String value){ th.set(value); } public void getTh(){ System.out.println(Thread.currentThread().getName() + ":" + this.th.get()); } public static void main(String[] args) throws InterruptedException { final ConnThreadLocal ct = new ConnThreadLocal(); Thread t1 = new Thread(new Runnable() { @Override public void run() { ct.setTh("张三"); ct.getTh(); } }, "t1"); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); ct.getTh(); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t2"); t1.start(); t2.start(); } } 

打印结果:

t1:张三t2:null
这个例子很简单,就是t1设置了ThreadLocal变量,可以获取得到,而t2获取为null,因为对ThreadLocal来说,其放置的变量时相对于每个线程独立一份。

转载地址:https://jeffsheng.blog.csdn.net/article/details/80561940 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:每天一例多线程[day12]-----单例模式与线程安全
下一篇:每天一例多线程[day9]-----多线程间的通信

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年04月06日 13时08分15秒