博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JAVA线程本地变量ThreadLocal和私有变量的区别
阅读量:4136 次
发布时间:2019-05-25

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

ThreadLocal并不是一个Thread,而是Thread的 ,也许把它命名为ThreadLocalVariable更容易让人理解一些。
所以,在Java中编写线程局部变量的代码相对来说要笨拙一些,因此造成线程局部变量没有在Java开发者中得到很好的普及。
ThreadLocal的接口方法
ThreadLocal类接口很简单,只有4个方法,我们先来了解一下:
void set(Object value)
public void remove()
将当前线程 的值删除,目的是为了减少内存的占用。
 
ThreadLocal的原理
在ThreadLocal类中有一个Map,用于
存储每一个线程的变量的副本。比如下面的示例实现:
public class ThreadLocal
private Map values = Collections.synchronizedMap(new HashMap());
public Object get()
{
Thread curThread = Thread.currentThread();
Object o = values.get(curThread);
if (o == null && !values.containsKey(curThread))
{
o = initialValue();
values.put(curThread, o);
}
values.put(Thread.currentThread(), newValue);
return o ;
}
public Object initialValue()
{
return null;
}
}
 
 
演示代码
 
public class ThreadLocalExample {    public static class MyRunnable implements Runnable {        private ThreadLocal
threadLocal = new ThreadLocal
(); int local = 0; @Override public void run() { threadLocal.set((int) (Math.random() * 100D)); local = (int) (Math.random() * 100D); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("threadLocal:" +threadLocal.get()); System.out.println("local:" +local); } } public static void main(String[] args) { MyRunnable sharedRunnableInstance = new MyRunnable(); Thread thread1 = new Thread(sharedRunnableInstance); Thread thread2 = new Thread(sharedRunnableInstance); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // wait for thread 1 to terminate // wait for thread 2 to terminate }}

 

转载地址:http://yxpvi.baihongyu.com/

你可能感兴趣的文章
基于linux的3款压力测试工具:Siege、webbench、ab
查看>>
FC8下安装Zend Studio5.1.0时遇到的问题及解决方法
查看>>
HTML中小meta的大作用
查看>>
修改注册表来加快HTTP上传速度
查看>>
[问题解决]Visio“搜索形状"不能用
查看>>
JS匹配任意字符的正则表达式写法
查看>>
JavaScript 字符串匹配性能比较
查看>>
CSS 背景偏移技术详解
查看>>
淡淡Cookie存取和IE页面缓存的问题
查看>>
XML中特殊字符的处理
查看>>
ping命令查看对方操作系统
查看>>
解决ssh中文乱码
查看>>
ubuntu下nutch-1.0的安装和配置错误排除
查看>>
Eclipse中program arguments 与 VM arguments的区别
查看>>
Nutch“java.lang.NoClassDefFoundError:”问题解决
查看>>
nutch "Job failed!" 问题解决
查看>>
解决nutch搜不到结果
查看>>
从零开始搭建nutch搜索引擎
查看>>
C++默认参数
查看>>
正则表达式中有用但很少用的语法
查看>>