实例1:
package com.bijian.thread; public class MyThread extends Thread { private static ThreadLocal tl = new ThreadLocal() { protected synchronized Object initialValue() { return new Integer(sernum++); } }; private static int sernum = 100; MyThread(String name) { super(name); } public void run() { for (int i = 0; i < 5; i++) System.out.println(getName() + " " + tl.get()); } }
package com.bijian.thread; public class ThreadLocalDemo1 { public static void main(String[] args) { MyThread mt1 = new MyThread("A"); MyThread mt2 = new MyThread("B"); MyThread mt3 = new MyThread("C"); mt1.start(); mt2.start(); mt3.start(); } }
运行结果:
C 101 A 100 B 102 A 100 C 101 A 100 B 102 A 100 C 101 A 100 B 102 C 101 B 102 C 101 B 102
实例2:
package com.bijian.thread; public class MyThread extends Thread { private static ThreadLocal tl = new ThreadLocal(); private static int sernum = 100; MyThread(String name) { super(name); } public void run() { synchronized ("A") { tl.set("" + sernum++); } for (int i = 0; i < 10; i++) System.out.println(getName() + " " + tl.get()); } }
package com.bijian.thread; public class ThreadLocalDemo2 { public static void main(String[] args) { MyThread mt1 = new MyThread("A"); MyThread mt2 = new MyThread("B"); MyThread mt3 = new MyThread("C"); mt1.start(); mt2.start(); mt3.start(); } }
运行结果:
A 100 B 101 A 100 C 102 A 100 B 101 A 100 C 102 A 100 B 101 C 102 B 101 C 102 B 101 C 102