zoukankan      html  css  js  c++  java
  • 多线程(二)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();
        }
    
    }

      

  • 相关阅读:
    String的几种初始化方法的区别
    Java编程思想之字符串
    树图 广度优先算法和深度优先算法
    bzoj1047: [HAOI2007]理想的正方形
    bzoj3124: [Sdoi2013]直径
    bzoj3930: [CQOI2015]选数
    bzoj1222: [HNOI2001]产品加工
    bzoj3578: GTY的人类基因组计划2
    bzoj4444: [Scoi2015]国旗计划
    bzoj1040: [ZJOI2008]骑士
  • 原文地址:https://www.cnblogs.com/deepSleeping/p/10259139.html
Copyright © 2011-2022 走看看