Java中ThreadLocal的用法

作为线程的本地副本,每个线程的值都是独立的,并且在线程结束之后自动资源释放,也可以手动remove。

        ThreadLocal threadLocal = new ThreadLocal<>();

        new Thread(() -> {
            threadLocal.set("apple");
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadLocal.get());
        }).start();

        new Thread(() -> {
            threadLocal.set("banana");
            try {
                Thread.sleep(2000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadLocal.get());
        }).start();

        new Thread(() -> {
            threadLocal.set("pear");
            try {
                Thread.sleep(3000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(threadLocal.get());
        }).start();

输出的结果为:

apple
banana
pear

线程间的结果互不影响。

你可能感兴趣的:(Java并发编程)