+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1more examplescc0c4d5

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