[关闭]
@Fancy-Bai 2015-03-03T11:11:30.000000Z 字数 1375 阅读 1736

深入研究java.lang.ThreadLocal类

Java,Java源码学习


java.lang.ThreadLocal示例:

  1. import java.util.Random;
  2. /**
  3. * <code>java.lang.ThreadLocal</code>简单示例
  4. * <p>@Author baininghan
  5. * <p>@Date 2015年3月3日
  6. * <p>@version 1.0
  7. *
  8. */
  9. public class ThreadLocalDemo implements Runnable{
  10. private static final ThreadLocal<Student> threadLocal = new ThreadLocal<Student>();
  11. public static void main(String[] args) {
  12. ThreadLocalDemo demo = new ThreadLocalDemo();
  13. Thread t1 = new Thread(demo, "t1");
  14. Thread t2 = new Thread(demo, "t2");
  15. t1.start();
  16. t2.start();
  17. }
  18. @Override
  19. public void run() {
  20. Student student = getStudent();
  21. student.setAge(new Random().nextInt(100));
  22. System.out.println("Thread[" + Thread.currentThread().getName() + "] is running...");
  23. System.out.println("First read Student's age : " + student.getAge());
  24. try {
  25. Thread.sleep(1000);
  26. } catch (InterruptedException e) {
  27. e.printStackTrace();
  28. }
  29. System.out.println("Second read Student's age : " + student.getAge());
  30. clearStudent();
  31. }
  32. public Student getStudent(){
  33. // 获取当前线程调用对象的一个局部变量(副本)
  34. Student student = threadLocal.get();
  35. // 第一次调用 get(),执行的是initialValue(),返回肯定是null,可以通过重写initialValue()方法,获得自己的返回值
  36. // 第二次调用就会得到set()设置进去的值
  37. if(student == null){
  38. student = new Student();
  39. threadLocal.set(student);
  40. }
  41. return student;
  42. }
  43. /** 回收Student */
  44. public void clearStudent(){
  45. Student student = threadLocal.get();
  46. threadLocal.set(null);
  47. if(student != null){
  48. student = null;
  49. }
  50. }
  51. class Student {
  52. private int age;
  53. public void setAge(int age){
  54. this.age = age;
  55. }
  56. public int getAge(){
  57. return age;
  58. }
  59. }
  60. }

参考链接:
1. 深入研究java.lang.ThreadLocal类
2. 作者个人博客

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注