ThreadLocal例子
2015-04-28 本文已影响24人
几千里也
public class ThreadLocalDemo {
public static class MyRunnable implements Runnable {
// The ThreadLocal class in Java enables you to create variables that
// can only be read and written by the same thread. Thus, even if two
// threads are executing the same code, and the code has a reference to
// a ThreadLocal variable, then the two threads cannot see each other's
// ThreadLocal variables.
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
// you can specify an initial value for a ThreadLocal object by
// subclassing ThreadLocal and overriding the initialValue() method.
@Override
protected Integer initialValue() {
return 123456789; // It is visible to all threads.
}
};
@Override
public void run() {
String threadName = Thread.currentThread().getName();
// All threads will see the same initial value when calling get()
// before having called set().
System.out.println(threadName + ", init: " + threadLocal.get());
threadLocal.set((int) (Math.random() * 100D));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
// If two different threads set different values on the same
// ThreadLocal object, they cannot see each other's values.
System.out.println(threadName + ", random: " + threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
/* Console:
Thread-0, init: 123456789
Thread-1, init: 123456789
Thread-1, random: 82
Thread-0, random: 95
*/
}
}