SharedValue_UseThreadLocal.java
package egtry.thread;
public class SharedValue_UseThreadLocal extends Thread {
private static ThreadLocal<Long> threadLocal=new ThreadLocal<Long>(); //long value inside ThreadLocal
public static void main(String[] args) throws Exception {
SharedValue_UseThreadLocal thread1=new SharedValue_UseThreadLocal();
thread1.start();
SharedValue_UseThreadLocal thread2=new SharedValue_UseThreadLocal();
thread2.start();
SharedValue_UseThreadLocal thread3=new SharedValue_UseThreadLocal();
thread3.start();
}
@Override
public void run() {
Thread t=Thread.currentThread();
long id=t.getId();
for(long i=0; i<100; i++) {
threadLocal.set(id); //update the value of the ThreadLocal.
Sleep(10); //hold the execution for 10 milliseconds
if (id !=threadLocal.get()) {
System.out.println(id+": ERROR: val was modified by other thread");
break;
}
}
System.out.println("thread id="+t.getId()+", threadlocal variable value="+threadLocal.get());
}
public static void Sleep(int ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Output
thread id=8, threadlocal variable value=8
thread id=9, threadlocal variable value=9
thread id=10, threadlocal variable value=10