Java ThreadLocal (Java代码实战-006)

 java代码:

package Threads;

import java.util.concurrent.CountDownLatch;

/**
 * Created by xfyou 2018/5/25 18:32.
 */
public class ThreadLocalDemo {

    // 闭锁需要等待的线程数量
    private static final int THREADS_COUNT = 3;

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

        /*在实时系统中的使用场景
         *
         * 实现最大的并行性:有时我们想同时启动多个线程,实现最大程度的并行性。
         * 例如,我们想测试一个单例类。如果我们创建一个初始计数为1的CountDownLatch,并让所有线程都在这个锁上等待,那么我们可以很轻松地完成测试。我们只需调用一次countDown()方法就可以让所有的等待线程同时恢复执行。
         * 开始执行前等待N个线程完成各自任务:例如应用程序启动类要确保在处理用户请求前,所有N个外部系统已经启动和运行了。
         * 死锁检测:一个非常方便的使用场景是,你可以使用N个线程访问共享资源,在每次测试阶段的线程数目是不同的,并尝试产生死锁。
         */
        CountDownLatch countDownLatch = new CountDownLatch(THREADS_COUNT);

        InnerClass innerClass = new InnerClass();
        for (int i = 1; i <= THREADS_COUNT; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 4; j++) {
                        innerClass.add(String.valueOf(j));
                        innerClass.print();
                    }
                    innerClass.set("hello world");

                    /*
                     * 通知CountDownLatch对象,他们已经完成了各自的任务
                     * 每当一个线程完成了自己的任务后,计数器的值就会减1
                     * 所以当N个线程都调用了这个方法,count的值等于0,然后主线程就能通过await()方法,恢复执行自己的任务。
                     */
                    countDownLatch.countDown();
                }
            }, "Thread-" + i).start();
        }

        /*
         * 主线程必须在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。
         * CountDownLatch是通过一个计数器来实现的,计数器的初始值为线程的数量。
         * 每当一个线程完成了自己的任务后,计数器的值就会减1。当计数器值到达0时,它表示所有的线程已经完成了任务,然后在闭锁(Latch)上等待的线程就可以恢复执行任务。
         */
        countDownLatch.await();

        System.out.println("所有线程执行完毕");
        System.out.println("主线程继续执行。。。");
    }

    private static class InnerClass {
        void add(String newStr) {
            StringBuilder str = Counter.counter.get();
            Counter.counter.set(str.append(newStr));
        }

        void print() {
            System.out.printf("Thread name:%s , ThreadLocal hashcode:%s, Instance hashcode:%s, Value:%s\n",
                    Thread.currentThread().getName(),
                    Counter.counter.hashCode(),
                    Counter.counter.get().hashCode(),
                    Counter.counter.get().toString());
        }

        void set(String words) {
            Counter.counter.set(new StringBuilder(words));
            System.out.printf("Set, Thread name:%s , ThreadLocal hashcode:%s,  Instance hashcode:%s, Value:%s\n",
                    Thread.currentThread().getName(),
                    Counter.counter.hashCode(),
                    Counter.counter.get().hashCode(),
                    Counter.counter.get().toString());
        }
    }

    private static class Counter {
        /*
         * get时如果线程本地变量为null,则默认初始化一个这个变量类型的实例。
         * StringBuilder为非线程安全的类型,通过ThreadLocal本地化则可以实现线程安全
         */
        private static ThreadLocal<StringBuilder> counter = new ThreadLocal<StringBuilder>() {
            @Override
            protected StringBuilder initialValue() {
                return new StringBuilder();
            }
        };
    }
}

 一种可能的运行结果如下:

Thread name:Thread-2 , ThreadLocal hashcode:946838393, Instance hashcode:537578880, Value:0
Thread name:Thread-2 , ThreadLocal hashcode:946838393, Instance hashcode:537578880, Value:01
Thread name:Thread-2 , ThreadLocal hashcode:946838393, Instance hashcode:537578880, Value:012
Thread name:Thread-2 , ThreadLocal hashcode:946838393, Instance hashcode:537578880, Value:0123
Set, Thread name:Thread-2 , ThreadLocal hashcode:946838393,  Instance hashcode:997620193, Value:hello world

Thread name:Thread-3 , ThreadLocal hashcode:946838393, Instance hashcode:767376320, Value:0
Thread name:Thread-3 , ThreadLocal hashcode:946838393, Instance hashcode:767376320, Value:01
Thread name:Thread-3 , ThreadLocal hashcode:946838393, Instance hashcode:767376320, Value:012
Thread name:Thread-3 , ThreadLocal hashcode:946838393, Instance hashcode:767376320, Value:0123
Set, Thread name:Thread-3 , ThreadLocal hashcode:946838393,  Instance hashcode:595251207, Value:hello world

Thread name:Thread-1 , ThreadLocal hashcode:946838393, Instance hashcode:540065051, Value:0
Thread name:Thread-1 , ThreadLocal hashcode:946838393, Instance hashcode:540065051, Value:01
Thread name:Thread-1 , ThreadLocal hashcode:946838393, Instance hashcode:540065051, Value:012
Thread name:Thread-1 , ThreadLocal hashcode:946838393, Instance hashcode:540065051, Value:0123
Set, Thread name:Thread-1 , ThreadLocal hashcode:946838393,  Instance hashcode:787957613, Value:hello world

所有线程执行完毕
主线程继续执行。。。

 运行结果分析:

1、所有线程访问的都是同一个ThreadLocal变量,其hashcode为:946838393(各线程访问的ThreadLocal在堆内存中的地址均为同一个);

2、各线程通过ThreadLocal对象的get()方法拿到的StringBuilder对象实例是不同的(hashcode不一样,实例在堆内存中的地址不一样);

3、各个线程将字符串追加进各自的 StringBuidler 实例内;

4、使用 set(T t) 方法后,ThreadLocal 变量所指向的 StringBuilder 实例被替换。

猜你喜欢

转载自www.cnblogs.com/frankyou/p/9099252.html