zoukankan      html  css  js  c++  java
  • 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 类的实现就是采用的这种思想,注意只是思想,实际的实现和上面的并不一样。

     

  • 相关阅读:
    LeetCode105 从前序遍历和中序遍历构造二叉树
    LeetCode61 扑克牌中的顺子
    LeetCode141 环形链表
    LeetCode103 二叉树的锯齿形层次遍历
    509 斐波那契数
    剑指29 顺时针打印矩阵
    malloc分配内存2种方式:brk和mmap
    Python学习第139天(Django的分页器(paginator))
    Python学习第138天(Django的用户认真组件)
    Python学习第137天(admin部分参数补充)
  • 原文地址:https://www.cnblogs.com/yaowen/p/10913143.html
Copyright © 2011-2022 走看看