多线程ThreadLocal

Posted deepsleeping

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程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();
    }

}

 

  

技术分享图片

 

以上是关于多线程ThreadLocal的主要内容,如果未能解决你的问题,请参考以下文章

JAVA多线程提高三:线程范围内共享变量&ThreadLocal

ThreadLocal 源码分析

多线程

多线程-ThreadLocal的使用

Java多线程_ThreadLocal

java多线程18: ThreadLocal的作用