ThreadLocal

ThreadLocal 的实例可以只有一个;
里面的值适合放线程里new的实例对象;
放全局的变量, 改变ThreadLocal.get获取的对象之后该全局变量也就真的改变了;

public class TLDemo {

    public static TLModel tlModel = new TLModel("string");
    static  ThreadLocal<TLModel> tls = new ThreadLocal<TLModel>() {
        @Override
        protected TLModel initialValue() {
            return new TLModel("df");
        }
    };

    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {

            @Override
            public void run() {
                threadRun("thread1");
            }
        });
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                threadRun("thread2");
            }
        });
        Thread thread3 = new Thread(new Runnable() {

            @Override
            public void run() {
                threadRun("thread3");
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }

    public static void threadRun(String name) {
        // InheritableThreadLocal<TLModel> tls = new
        // InheritableThreadLocal<TLModel>();
        tls.set(new TLModel(name));
        System.out.println(name + "运行前--" + tls.get().getString());
        tls.get().setString(name);
        System.out.println(name + "改变后--" + tls.get().getString());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(name + "睡眠后--" + tls.get().getString());
    }

    public static class TLModel {
        private String string;

        public TLModel(String string) {
            this.string = string;
        }

        public String getString() {
            return string;
        }

        public void setString(String string) {
            this.string = string;
        }
    }
}

results matching ""

    No results matching ""