博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程学习(十)
阅读量:4322 次
发布时间:2019-06-06

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

线程本地存储

防止任务在共享资源上产生冲突的第二种方式就是根除对线程的共享,线程本地存储一种自动化机制。可以为使用相同变量的每个不同的线程都创建不同的存储。如果你有5个线程要使用变量X所表示的对象,那么线程本地存储就会生成5个用于x的不同的存储块。主要是 可以使得线程与状态关联起来。

public class ThreadLocalVariableHolder {    private static ThreadLocal
value = new ThreadLocal
() { @Override protected Integer initialValue() { // TODO Auto-generated method stub return 0; } }; public static void increment() { value.set(value.get() + 1); } public static Integer get() { return value.get(); } public static void set(int a) { value.set(a); }}
public class ThreadlocalTest implements Runnable {    private int initValue;    public ThreadlocalTest(int initValue) {        super();        this.initValue = initValue;        ThreadLocalVariableHolder.set(initValue);    }    @Override    public void run() {        // TODO Auto-generated method stub        while (!Thread.currentThread().isInterrupted()) {            ThreadLocalVariableHolder.increment();            System.out.println(this);        }    }    @Override    public String toString() {        return "#id(" + Thread.currentThread().getId() + ")" + ThreadLocalVariableHolder.get();    }    public static void main(String[] args) throws Exception {        ExecutorService exec = Executors.newCachedThreadPool();        Runnable target = new ThreadlocalTest(0);        for (int i = 0; i < 5; i++) {            exec.execute(target);        }                TimeUnit.MILLISECONDS.sleep(50);                exec.shutdownNow();    }}

转载于:https://www.cnblogs.com/joeCqupt/p/6826984.html

你可能感兴趣的文章
学习进度
查看>>
使用Postmark测试后端存储性能
查看>>
NSTextView 文字链接的定制化
查看>>
第五天站立会议内容
查看>>
最短路径(SP)问题相关算法与模板
查看>>
js算法之最常用的排序
查看>>
Python——交互式图形编程
查看>>
经典排序——希尔排序
查看>>
团队编程项目作业2-团队编程项目代码设计规范
查看>>
英特尔公司将停止910GL、915GL和915PL芯片组的生产
查看>>
Maven配置
查看>>
HttpServletRequest /HttpServletResponse
查看>>
SAM4E单片机之旅——24、使用DSP库求向量数量积
查看>>
从远程库克隆库
查看>>
codeforces Unusual Product
查看>>
hdu4348 - To the moon 可持久化线段树 区间修改 离线处理
查看>>
正则表达式的搜索和替换
查看>>
个人项目:WC
查看>>
地鼠的困境SSL1333 最大匹配
查看>>
flume+elasticsearch+kibana遇到的坑
查看>>