import java.util.Random;/*** ThreadLocal實例* 源自http://lavasoft.blog.51cto.com/62575/51926/* @author yinchuan.chen**/public class ThreadLocalDemo implements Runnable {//創建線程局部變量studentLocal,在后面你會發現用來保存Student對象PRivate final static ThreadLocal studentLocal = new ThreadLocal();public static void main(String[] agrs) {ThreadLocalDemo td = new ThreadLocalDemo();Thread t1 = new Thread(td, "a");Thread t2 = new Thread(td, "b");t1.start();t2.start();}public void run() {accessStudent();}/*** 示例業務方法,用來測試*/public void accessStudent() {//獲取當前線程的名字String currentThreadName = Thread.currentThread().getName();System.out.println(currentThreadName + " is running!");//產生一個隨機數并打印Random random = new Random();int age = random.nextInt(100);System.out.println("thread " + currentThreadName + " set age to:" + age);//獲取一個Student對象,并將隨機數年齡插入到對象屬性中Student student = getStudent();student.setAge(age);System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge());try {Thread.sleep(500);}catch (InterruptedException ex) {ex.printStackTrace();}System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge());}protected Student getStudent() {//獲取本地線程變量并強制轉換為Student類型Student student = (Student) studentLocal.get();//線程首次執行此方法的時候,studentLocal.get()肯定為nullif (student == null) {//創建一個Student對象,并保存到本地線程變量studentLocal中student = new Student();studentLocal.set(student);}return student;}}class Student {private int age = 0; //年齡public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}}
本文源自http://lavasoft.blog.51cto.com/62575/51926/
新聞熱點
疑難解答