public class TestThreadLocal {
    private static ThreadLocal<String> threadLocal;

    public static void main(String[] args) {

        threadLocal = new ThreadLocal<String>() {

            @Override
            protected String initialValue() {
                return "Initialize value"; }};for(int i = 0; i < 10; I ++){// I ==1 uses the initialization valueif(i==1){
                new Thread(new MyRunnable(),"default").start();
            }else{
                new Thread(new MyRunnable(), "Thread"+i).start();
            }
        }

    }

    public static class MyRunnable implements Runnable {

        @Override
        public void run() {
            String name = Thread.currentThread().getName();
            System.out.println(name + "The threadLocal"+ ", set to" + name);
            if(name ! ="default")
                threadLocal.set(name);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
            System.out.println(name + ":"+ threadLocal.get()); }}}Copy the code