+/EE360P
distributed systems
git clone https://git.julia.blue/+/EE360P
5a5a002
master
1// http://tutorials.jenkov.com/java-concurrency/threadlocal.html 2public class ThreadLocalExample { 3 4 5public static class MyRunnable implements Runnable { 6 7private ThreadLocal <Integer >threadLocal = 8new ThreadLocal <Integer >(); 9 10@ Override 11public void run () { 12threadLocal .set ( (int ) (Math .random () *100D ) ); 13System .out .println (Thread .currentThread ().getName () +" has value " +threadLocal .get ()); 14 15try { 16Thread .sleep (2000 ); 17 }catch (InterruptedException e ) { 18 } 19 20System .out .println (Thread .currentThread ().getName () +" has value " +threadLocal .get ()); 21 } 22 } 23 24 25public static void main (String []args )throws InterruptedException { 26MyRunnable sharedRunnableInstance =new MyRunnable (); 27 28Thread thread1 =new Thread (sharedRunnableInstance ,"Thread 1" ); 29Thread thread2 =new Thread (sharedRunnableInstance ,"Thread 2" ); 30 31thread1 .start (); 32thread2 .start (); 33 34thread1 .join ();//wait for thread 1 to terminate 35thread2 .join ();//wait for thread 2 to terminate 36 } 37 38} 39