多线程之:ThreadLocal

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

InheritableThreadLocal

ThreadLocal的子类,允许一个线程创建的所有子线程访问其父线程的值,解决了ThreadLocal实例内部每个线程都只能看到自己的私有值的问题。

posted on 2015-11-29 18:51  jessezeng  阅读(289)  评论(0编辑  收藏  举报

导航