ThreadLocal 例子
2017-11-27 13:39 faunjoe88 阅读(249) 评论(0) 编辑 收藏 举报/** * 一个ThreadLocal代表一个变量,故其中里只能放一个数据,有两个变量都要线程内共享,则要定义两个ThreadLocal。 */ public class ThreadLocalTest { private static ThreadLocal<Integer> threadData = new ThreadLocal<Integer>(); public static void main(String[] args) { for (int i = 0; i < 2; i++) { new Thread(new Runnable() { public void run() { int data = new Random().nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.set(data); new A().get(); new B().get(); } }).start(); } } static class A { public void get() { int data = threadData.get(); System.out.println("A from " + Thread.currentThread().getName() + " get data: " + data); } } static class B { public void get() { int data = threadData.get(); System.out.println("B from " + Thread.currentThread().getName() + " get data: " + data); } } }
输出结果:
Thread-1 has put data :-1978178521 Thread-0 has put data :-227790491 A from Thread-0 get data: -227790491 A from Thread-1 get data: -1978178521 B from Thread-0 get data: -227790491 B from Thread-1 get data: -1978178521