+/EE360P

distributed systems

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

vijaygarg1more examplescc0c4d5

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