省流:构造方法在主线程里跑的
先贴代码
public class Test { @SneakyThrows public static void main(String[] args) { ExecutorService execute = Executors.newSingleThreadExecutor(); execute.execute(new T1("once")); execute.execute(new T1(null)); Thread.sleep(1000); execute.shutdownNow(); } static class T1 implements Runnable { static final ThreadLocal<String> str = new ThreadLocal<>(); @SneakyThrows public T1(String a) { if (a != null){ str.set(a); System.out.println("set str"); } } @Override public void run() { System.out.println(Thread.currentThread().getId()); System.out.println(str.get()); } } }
期望输出:
set str
线程id
once
线程id
null
实际输出:
问题分析步骤:
debug分析 摇人最快
@SneakyThrows public T1(String a) { if (a != null){ System.out.println(Thread.currentThread().getId()); str.set(a); System.out.println("set str"); } }
在这打印下线程号,执行一下问题就知道了
标签:execute,set,构造方法,System,T1,---,ThreadLocal,str,public From: https://www.cnblogs.com/chiangkkk/p/17061572.html