这是我的第一篇博客,条理不是很清晰,不过还是希望能对大家有所帮助。 首先明确一下这个类的作用,ThreadLocal类是用来为每个线程提供了一份变量的副本,即每个线程的局部变量。每个线程都在自己的栈空间里存有这个变量的值(对象的话就是引用),它们之间是线程隔离的,一个线程对这个 ...
这是我的第一篇博客,条理不是很清晰,不过还是希望能对大家有所帮助。
首先明确一下这个类的作用,ThreadLocal类是用来为每个线程提供了一份变量的副本,即每个线程的局部变量。每个线程都在自己的栈空间里存有这个变量的值(对象的话就是引用),它们之间是线程隔离的,一个线程对这个ThreadLocal变量做的修改不会被其他线程看见。
下面先看一个例子。
1 import java.util.Random; 2 3 public class ThreadLocalTest { 4 private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>(){ 5 protected Integer initialValue() { 6 return 6; 7 } 8 }; 9 10 public static int get(){11 return threadId.get();12 }13 14 public static void main(String[] args) {15 new Thread(new MThread("线程A")).start();16 new Thread(new MThread("线程B")).start();17 new Thread(new MThread("线程C")).start(); 18 }19 20 static class MThread implements Runnable{21 private String name;22 public MThread(String str){23 name = str;24 }25 public void run() {26 int id = get();27 System.out.println("thread "+ name +"'s Id : "+ id);28 threadId.set(10 * new Random().nextInt(10));29 for(int i = 0; i<3; i++){30 id = get();31 System.out.println("**thread "+ name +"'s Id : "+ id);32 }33 }34 }35 }
原标题:浅析ThreadLocal
关键词:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。