标签:connected foreach thread rem tar connect trace style div
一个类对象类型,提供属线程本地变量,也就是同一个变量对不同线程保存了不同的值,但是和线程自身定义的自属变量不同。
通常以私有静态类型定义,用以保存特定线程特定状态属性。
线程存活期间保持对ThreadLocal的弱引用,线程结束后,则变量会被垃圾回收器回收。
//定义一个ThreadLocal变量用以存储不同线程的ID ThreadLocal<Long> localVs = new ThreadLocal<>(); //线程list List<Thread> threads = new ArrayList<>(); //初始化线程 IntStream.range(0, 5).forEach(value -> { Thread tmp = new Thread(() -> { //线程运行时(线程运行期间),将ID放入变量 localVs.set(Thread.currentThread().getId()); //输出当前线程名称,ID System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().getId()); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } //延迟3s,输出当前线程名称,所属ThreadLocal变量 System.out.println(Thread.currentThread().getName() + ": " + localVs.get()); }); threads.add(tmp); }); for (Thread thread : threads) { thread.start(); }
输出:
Thread-0: 12 Thread-2: 14 Thread-1: 13 Thread-4: 16 Thread-3: 15 Disconnected from the target VM, address: ‘127.0.0.1:59273‘, transport: ‘socket‘ Thread-1: 13 Thread-0: 12 Thread-2: 14 Thread-4: 16 Thread-3: 15
线程中使用ThreadLocal类型变量,在线程声明周期结束前调用ThreadLocal::remove()方法,清除对应本线程的变量内存占用,避免内存泄漏。
标签:connected foreach thread rem tar connect trace style div
原文地址:https://www.cnblogs.com/niejunlei/p/12729035.html