zoukankan      html  css  js  c++  java
  • ThreadLocal的简单使用(读书笔记)

         从ThreadLocal的名字上可以看到,这是一个线程局部变量,也就是说,只有当前线程可以访问,既然是只有当前线程可以访问的数据,自然是线程安全的.
    public class ThreadLocalDemo {
        private static ThreadLocal<SimpleDateFormat> t1 = new ThreadLocal<>();
    
        public static class ParseDate implements Runnable {
            int i = 0;
    
            public ParseDate(int i) {
                this.i = i;
            }
    
            /**
             * When an object implementing interface <code>Runnable</code> is used
             * to create a thread, starting the thread causes the object's
             * <code>run</code> method to be called in that separately executing
             * thread.
             * <p>
             * The general contract of the method <code>run</code> is that it may
             * take any action whatsoever.
             *
             * @see Thread#run()
             */
            @Override
            public void run() {
                try {
                    if (t1.get() == null)
                        t1.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
                    Date t = t1.get().parse("2015-03-29 19:29:" + i % 60);
                    System.out.println(i + ":" + t);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public static void main(String[] args) {
            ExecutorService es = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++) {
                es.execute(new ParseDate(i));
            }
    
        }
    }
         从这里也可以看到,为每一个线程人手分配一个对象工作并不是有ThreadLocal来完成的.而是需要在应用层面保证的,如果在应用上为每一个线程分配了相同的对象实例,那么ThreadLocal也不能保证线程安全,
  • 相关阅读:
    天正暖通2013版安装包附带注册机下载
    你妈安好
    利用FLASH和XML做炫酷图片相册
    空调冷凝水管径选用原则
    知足常乐
    曾经的真三国无双
    Deep Exploration安装破解汉化
    Revit模型文件输出为3D PDF格式的方法
    Adobe Acrobat 9 Pro Extended简体中文版安装破解汉化教程
    Keep reading
  • 原文地址:https://www.cnblogs.com/ten951/p/6212338.html
Copyright © 2011-2022 走看看