• 多线程(二)ThreadLocal


     ThreadLocal

    public class Demo extends Thread{
    
        static int i = 0;
        
        public Integer getNext(){
            
            i++;
            return i;
        }
        
        
        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                System.out.println(currentThread().getName() + "---" + getNext());
            }
        }
        
        
        public static void main(String[] args) {
            Demo demo = new Demo();
            Thread thread = new Thread(demo);
            thread.setName("线程1");
            Thread thread1 = new Thread(demo);
            thread1.setName("线程2");
            Thread thread2 = new Thread(demo);
            thread2.setName("线程3");
            thread.start();
            thread1.start();
            thread2.start();
        }
    
    }

    ThreadLocal将代码修改一下~

    package test;
    
    public class Demo extends Thread{
    
        static Integer i;
        
        
        ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
        
        public Integer getNext(){
            //从ThreadLocal中获取
            i = threadLocal.get();
            if (i == null) {
                i = 0;
            }
            i++;
            //存入ThreadLocal中
            threadLocal.set(i);
            return i;
        }
        
        
        @Override
        public void run() {
            for (int i = 0; i < 3; i++) {
                System.out.println(currentThread().getName() + "---" + getNext());
            }
        }
        
        
        public static void main(String[] args) {
            Demo demo = new Demo();
            Thread thread = new Thread(demo);
            thread.setName("线程1");
            Thread thread1 = new Thread(demo);
            thread1.setName("线程2");
            Thread thread2 = new Thread(demo);
            thread2.setName("线程3");
            thread.start();
            thread1.start();
            thread2.start();
        }
    
    }

      

  • 相关阅读:
    如何缓解考前紧张和焦虑
    **浅谈差分【复习】**
    杂题训练之十一
    浅谈dfs/Tarjan找环【复习】
    杂题训练之十一
    杂题训练之十
    动态规划训练之二十
    浅谈欧拉函数【复习】
    数论训练之五
    浅谈杨辉三角【复习】
  • 原文地址:https://www.cnblogs.com/deepSleeping/p/10259139.html
Copyright © 2020-2023  润新知