• ThreadLocal源代码2


    private static int nextIndex(int i, int len) {
        return ((i + 1 < len) ? i + 1 : 0);
    }
    private static int prevIndex(int i, int len) {
        return ((i - 1 >= 0) ? i - 1 : len - 1);
    }

    ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    try {
        threadLocal.set(new Session(1, "Misout的博客"));
        // 其它业务逻辑
    } finally {
        threadLocal.remove();
    }
    //还记得Hibernate的session获取场景吗?
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    //获取Session
    public static Session getCurrentSession(){
        Session session =  threadLocal.get();
        //判断Session是否为空,如果为空,将创建一个session,并设置到本地线程变量中
        try {
            if(session ==null&&!session.isOpen()){
                if(sessionFactory==null){
                    rbuildSessionFactory();// 创建Hibernate的SessionFactory
                }else{
                    session = sessionFactory.openSession();
                }
            }
            threadLocal.set(session);
        } catch (Exception e) {
            // TODO: handle exception
        }
     
        return session;
    }

     

     

    public class MultiThreadDemo { 
        public static void main(String[] args) throws InterruptedException {
            private int value = 0;
            Thread increaseThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        value = 10;
                        Thread.sleep(10);
                        System.out.println("increase value: " + value);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            Thread decreaseThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        value = -10;
                        Thread.sleep(10);
                        System.out.println("decrease value: " + value);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
    
            increaseThread.start();
            decreaseThread.start();
        }
    }

    public class SimpleImpl {  
    
        public static void main(String[] args) throws InterruptedException {
            private Map<Long, Integer> cacheMap = new HashMap<>();
            private int defaultValue = 0 ;
            
            Thread increaseThread = new Thread(new Runnable() {
                @Override
                public void run() { 
                    long id = Thread.currentThread().getId();
                    cacheMap.put(id, 10); 
                    Thread.sleep(10);
                    long id = Thread.currentThread().getId();
                    if (cacheMap.containsKey(id)) {
                        return cacheMap.get(id);
                    }
                    return defaultValue; 
                }
            });
    
            Thread decreaseThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    long id = Thread.currentThread().getId();
                    cacheMap.put(id, -10);
                    Thread.sleep(10);
                    long id = Thread.currentThread().getId();
                    if (cacheMap.containsKey(id)) {
                        return cacheMap.get(id);
                    }
                    return defaultValue;
                }
            });
    
            increaseThread.start();
            decreaseThread.start();
        }
    }

    public class SimpleImpl2 {
    
        public static class CommonThread extends Thread {
            Map<Integer, Integer> cacheMap = new HashMap<>();
        } 
    
        public static class Number {  
            public void increase() throws InterruptedException {
                 Integer id = this.hashCode();
                Map<Integer, Integer> cacheMap = (CommonThread) Thread.currentThread().cacheMap;
                cacheMap.put(id, 10);
                Thread.sleep(10);  
                return cacheMap.get(id); 
            }
    
            public void decrease() throws InterruptedException {
                Integer id = this.hashCode();
                Map<Integer, Integer> cacheMap = (CommonThread) Thread.currentThread().cacheMap;
                cacheMap.put(id, -10);
                Thread.sleep(10);   
                return cacheMap.get(id); 
            }
        }
    
        public static void main(String[] args) throws InterruptedException {
            final Number number = new Number();
            Thread increaseThread = new CommonThread() {
                @Override
                public void run() { 
                    number.increase(); 
                }
            };
    
            Thread decreaseThread = new CommonThread() {
                @Override
                public void run() { 
                    number.decrease(); 
                }
            };
            increaseThread.start();
            decreaseThread.start();
        }
    }

    在上面的实现中,当线程消亡之后,线程中 cacheMap 也会被回收,它当中存放的副本变量(value)也会被全部回收,并且 cacheMap 是线程私有的,不会出现多个线程同时访问一个 cacheMap 的情况。在 Java 中,ThreadLocal 类的实现就是采用的这种思想,注意只是思想,实际的实现和上面的并不一样。

     

  • 相关阅读:
    ThinkPHP Model+数据库的切换使用
    关于SSD安装系统的一些设置(PE安装win 7)
    PHP实现文件下载:header
    Thinkphp 使用PHPExcel导入,栗子
    Ueditor 的使用(这里以php+ci为例)
    js获取鼠标选中的文字内容
    WNMP 下 Nginx 配置 (使用了phpfind一键安装环境)
    javascript 实现 trim
    javascript 获取 CSS 样式表属性
    javascript 删除节点问题
  • 原文地址:https://www.cnblogs.com/yaowen/p/10913143.html
Copyright © 2020-2023  润新知