Thread local in java

Thread Local


The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to aThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.



public class Threadlocal {

    public static class MyRunnable implements Runnable {

        private int id;

        public MyRunnable(int id) {
            // TODO Auto-generated constructor stub
            this.id = id;
        }

        private ThreadLocal threadLocal = new ThreadLocal();

        @Override
        public void run() {
            threadLocal.set(id);

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }

            System.out.println(threadLocal.get());
        }
    }

    public static void main(String[] args) throws InterruptedException {

        MyRunnable sharedRunnableInstance = new MyRunnable(23);
        MyRunnable sharedRunnableInstance1 = new MyRunnable(34);

        Thread thread1 = new Thread(sharedRunnableInstance);
        Thread thread2 = new Thread(sharedRunnableInstance1);

        thread1.start();
        thread2.start();

        thread1.join(); // wait for thread 1 to terminate
        thread2.join(); // wait for thread 2 to terminate
    }

}

Comments

Popular posts from this blog

Proxy setting in java

Using logstash to import csv json files into elasticsearch

Kibana 4 Installation and Run as a service in ubuntu