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

多线程之:ThreadLocal

时间:2015-11-29 19:31:37      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

Java中ThreadLocal类可以使创建的变量只被同一个线程进行读和写操作,即使有多个线程同时执行同一段代码,并且这段代码中又有一个指向同一个ThreadLocal变量的引用,这些线程依然不能看到彼此ThreadLocal变量域,只能看到自己私有的ThreadLocal实例。

看看如下demo:

 1 public class MyThreadLocal {
 2     public static class IntegerRandom implements Runnable {
 3         private ThreadLocal<Integer> integerThreadLocal = new ThreadLocal<Integer>();
 4         public void run() {
 5             integerThreadLocal.set((int) (Math.random() * 100));
 6             try {
 7                 Thread.sleep(5000);
 8             } catch (InterruptedException e) {
 9                 e.printStackTrace();
10             }
11             System.out.println("ThreadLocal integer current value:"+integerThreadLocal.get());
12         }
13     }
14     public static void main(String[] args) {
15         IntegerRandom sharedIntegerRandom=new IntegerRandom();
16         new Thread(sharedIntegerRandom).start(); //should use join();
17         new Thread(sharedIntegerRandom).start(); //should use join();
18   } 
19 }

 

执行结果:

ThreadLocal integer current value:72
ThreadLocal integer current value:88

多线程之:ThreadLocal

标签:

原文地址:http://www.cnblogs.com/jessezeng/p/5005180.html

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