ThreadLocal和线程池


发表于 2017-12-04 14:20


今天发现,原来线程池中的线程,当执行完毕被放入线程池后,并不会清空线程中ThreadLocal里面的变量,例如:

public class Test {

	private static ThreadLocal<String> local = new ThreadLocal<>();

	public static void main(String[] args) {
		Executor executor = Executors.newFixedThreadPool(1);

		executor.execute(() -> {
			System.out.println(local.get());
			local.set("123");
			System.out.println(local.get());
			// local.remove();
		});

		executor.execute(() -> {
			System.out.println(local.get());
			local.set("1234");
			System.out.println(local.get());
		});

		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
		}

	}

}

在这种情况下,需要手动调用remove方法。


搜索