ThreadLocal学习
package test; public class Student { private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package test; public class StudentUtil { private static ThreadLocal<Student> studentThreadLocal = new ThreadLocal<Student>(); public static Student getStudent() { Student student = studentThreadLocal.get(); if (student == null) { student = new Student(); studentThreadLocal.set(student); } return student; } }
package test; import java.util.Random; public class ThreadLocalTest implements Runnable { @Override public void run() { String threadName = Thread.currentThread().getName(); System.err.println(threadName + " is running"); int age = new Random().nextInt(100); System.err.println(threadName + " set age:" + age); Student student = StudentUtil.getStudent(); student.setAge(age); System.out.println(threadName + " is first get age: " + student.getAge()); try { Thread.sleep(10000); } catch (InterruptedException e) { } System.out.println(threadName + " is second get age: " + student.getAge()); } }
package test; public class Main { public static void main(String[] args) { for (int i = 0; i < 5; i++) { new Thread(new ThreadLocalTest()).start(); } } }
运行结果