//定义一个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()方法,清除对应本线程的变量内存占用,避免内存泄漏。