美文网首页
ThreadLocal的简单使用

ThreadLocal的简单使用

作者: 陈灬大灬海 | 来源:发表于2019-01-11 12:34 被阅读0次
    public class TestThreadLocal {
        private static ThreadLocal<String> threadLocal;
    
        public static void main(String[] args) {
    
            threadLocal = new ThreadLocal<String>() {
    
                @Override
                protected String initialValue() {
                    return "初始化值";
                }
    
            };
    
            for (int i = 0; i < 10; i++){
                // i==1的话使用初始化值
                if(i==1){
                    new Thread(new MyRunnable(),"default").start();
                }else{
                    new Thread(new MyRunnable(), "线程"+i).start();
                }
            }
    
        }
    
        public static class MyRunnable implements Runnable {
    
            @Override
            public void run() {
                String name = Thread.currentThread().getName();
                System.out.println(name + "的threadLocal"+ ",设置为" + name);
                if(name != "default")
                    threadLocal.set(name);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
                System.out.println(name + ":" + threadLocal.get());
            }
    
        }
    }
    

    相关文章

      网友评论

          本文标题:ThreadLocal的简单使用

          本文链接:https://www.haomeiwen.com/subject/itqxdqtx.html