+/EE360P

distributed systems

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

vijaygarg1added Tutorial examples5a5a002

master
1.1 KiB39 linesraw
1// http://tutorials.jenkov.com/java-concurrency/threadlocal.html
2public class ThreadLocalExample {
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 value " + threadLocal.get());
14    
15            try {
16                Thread.sleep(2000);
17            } catch (InterruptedException e) {
18            }
19    
20            System.out.println(Thread.currentThread().getName() + " has value " + threadLocal.get());
21        }
22    }
23
24
25    public static void main(String[] args) throws InterruptedException {
26        MyRunnable sharedRunnableInstance = new MyRunnable();
27
28        Thread thread1 = new Thread(sharedRunnableInstance, "Thread 1");
29        Thread thread2 = new Thread(sharedRunnableInstance, "Thread 2");
30
31        thread1.start();
32        thread2.start();
33
34        thread1.join(); //wait for thread 1 to terminate
35        thread2.join(); //wait for thread 2 to terminate
36    }
37
38}
39