+/EE360P
distributed systems
git clone https://git.julia.blue/+/EE360P
cc0c4d5
master
1// http://tutorials.jenkov.com/java-concurrency/threadlocal.html 2public class ThreadLocalExample3 { 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 ThreadLocal " +threadLocal .get ()); 14 15int plain = (int ) (Math .random () *100D ) ; 16System .out .println (Thread .currentThread ().getName () +" has plain " +plain ); 17 18try { 19Thread .sleep (2000 ); 20 }catch (InterruptedException e ) { 21 } 22 23System .out .println (Thread .currentThread ().getName () +" has ThreadLocal " +threadLocal .get ()); 24System .out .println (Thread .currentThread ().getName () +" has plain " +plain ); 25 } 26 } 27 28 29public static void main (String []args )throws InterruptedException { 30MyRunnable sharedRunnableInstance =new MyRunnable (); 31 32Thread thread1 =new Thread (sharedRunnableInstance ,"Thread 1" ); 33Thread thread2 =new Thread (sharedRunnableInstance ,"Thread 2" ); 34 35thread1 .start (); 36thread2 .start (); 37 38thread1 .join ();//wait for thread 1 to terminate 39thread2 .join ();//wait for thread 2 to terminate 40 } 41 42} 43