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

     

  • 相关阅读:
    从n个数中随机选出k个数,并判断和是不是素数
    最小生成树模板——给出两点和权值
    leetcode 538. 把二叉搜索树转换为累加树 【时间击败100.00%】 【内存击败96.46%】
    leetcode 100. 相同的树【 时间击败100.00%】 【内存击败83.99%】
    leetcode 572. 另一个树的子树 【时间击败88.10%】 【内存击败96.40%】
    java中hashmap的实现原理
    Java的int和Integer
    LeetCode 26. 删除排序数组中的重复项 【时间击败100.00%】 【内存击败95.37%】
    LeetCode 25. K 个一组翻转链表 【时间击败99.35%】 【内存击败74.50%】
    LeetCode 24. 两两交换链表中的节点 【时间击败100.00%】 【内存击败86.60%】
  • 原文地址:https://www.cnblogs.com/yaowen/p/10913143.html
Copyright © 2011-2022 走看看