编程语言
首页 > 编程语言> > 并发编程 - ThreadLocal 用法

并发编程 - ThreadLocal 用法

作者:互联网

ThreadLocal 类: 用来提供线程内部的局部变量。 这种变量在线程的生命周期内起作用,减少同一个线程内多个函数或者组件之间一些公共变量的传递的复杂度

 

public class AnswerApp {

    private static ThreadLocal<Integer> value = ThreadLocal.withInitial(() -> 0);

    public static void main(String[] args) {

        ExecutorService executors = Executors.newCachedThreadPool();

        for (int i = 1; i <= 5; i++) {
            executors.execute(new MyRunnable(i));

            // 线程 main 的累加值
            value.set(value.get() + i);
        }

        System.out.println(Thread.currentThread().getName() + "'s summation value: " + value.get());
    }


    static class MyRunnable implements Runnable {
        private int index;

        MyRunnable(int index) {
            this.index = index;
        }

        @Override
        public void run() {
            System.out.println("thread " + index + "'s init value: " + value.get());

            for (int i = 0; i < 10; i++) {
                value.set(value.get() + i);
            }

            System.out.println("thread " + index + "'s summation value: " + value.get());
        }
    }

}

 

thread 1's init value: 0
thread 3's init value: 0
main's summation value: 15
thread 2's init value: 0
thread 5's init value: 0
thread 3's summation value: 45
thread 1's summation value: 45
thread 4's init value: 0
thread 5's summation value: 45
thread 2's summation value: 45
thread 4's summation value: 45

 

Reference

标签:45,thread,编程,value,并发,ThreadLocal,线程,summation
来源: https://blog.csdn.net/u010979642/article/details/90673010