首页 > 编程语言 > 详细

多线程(二)ThreadLocal

时间:2019-01-12 12:55:27      阅读:216      评论:0      收藏:0      [点我收藏+]

 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();
    }

}

 

  

技术分享图片

 

多线程(二)ThreadLocal

原文:https://www.cnblogs.com/deepSleeping/p/10259139.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!