ThreadLocal例子

作者: 几千里也 | 来源:发表于2015-04-28 11:37 被阅读24次
public class ThreadLocalDemo {

    public static class MyRunnable implements Runnable {

        // 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
        // a ThreadLocal variable, then the two threads cannot see each other's
        // ThreadLocal variables.
        private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {

            // you can specify an initial value for a ThreadLocal object by
            // subclassing ThreadLocal and overriding the initialValue() method.
            @Override
            protected Integer initialValue() {
                return 123456789; // It is visible to all threads.
            }
        };

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();

            // All threads will see the same initial value when calling get()
            // before having called set().
            System.out.println(threadName + ", init: " + threadLocal.get());

            threadLocal.set((int) (Math.random() * 100D));

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

            // If two different threads set different values on the same
            // ThreadLocal object, they cannot see each other's values.
            System.out.println(threadName + ", random: " + threadLocal.get());
        }
    }

    public static void main(String[] args) {
        MyRunnable sharedRunnableInstance = new MyRunnable();

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

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

        /* Console:
        Thread-0, init: 123456789
        Thread-1, init: 123456789
        Thread-1, random: 82
        Thread-0, random: 95
        */
    }
}

相关文章

网友评论

    本文标题:ThreadLocal例子

    本文链接:https://www.haomeiwen.com/subject/rmlvfttx.html