public class ThreadLocalExample {
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
// private static Integer number = new Integer(1);
public static class MyRunnable implements Runnable {
@Override
public void run() {
threadLocal.set((int) (Math.random() * 100));
// number = (int) (Math.random() * 100);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println(threadLocal.get());
// System.out.println(number);
}
}
public static void main(String[] args) throws InterruptedException {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
Thread.sleep(1000);
threadLocal.set(10);
System.out.println(threadLocal.get());
// number = 10;
// System.out.println(number);
thread1.join(); // wait for thread 1 to terminate
thread2.join(); // wait for thread 2 to terminate
}
}