在本文中,我们首先讲述了为什么要有局部线程变量,然后通过一系列的案例来演示局部线程变量ThreadLocal到底有什么作用。
ThreadLocal局部线程变量是什么?
ThreadLocal的实例代表了一个线程局部的变量,每条线程都只能看到自己的值,并不会影响到其它线程中也存在的该变量。
用于解决多线程并发访问出现的问题。
ThreadLocal让线程A与线程B的变量相互隔离,每个线程只能访问到自己的值。例如线程A的执行顺序为1-2-3,当线程A执行到2时,线程B 访问到线程A 的2,此时就会导致一系列的访问问题。所以ThreadLocal的使用时很有必要的。
如何去使用它?
实现以下功能
三个线程中的变量同时自增,打印输出结果。
package com.example.thread;
import java.util.Random;
import com.example.Demo;
public class RobotThread implements Runnable{
/**
* 线程的名称
*/
private String name;
public RobotThread(String name)
{
this.name=name;
}
/**
* 线程局部变量
*/
private static ThreadLocal<Integer> variable = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 0;
}
};
/**
* 线程启动
*/
@Override
public void run() {
/**
* 一共进行三个步骤A->B->C,分为不同的时刻执行
*/
for(int i=1;i<=3;i++)
{
Random r=new Random();
int time=r.nextInt(10);
try {
Thread.sleep(time*200);
} catch (InterruptedException e) {
e.printStackTrace();
}
variable.set(i);
System.out.println("当前的步骤:"+variable.get()+",当前的线程Id:"+Thread.currentThread().getId()+"当前线程的名称:"+name);
}
}
public static void main(String []args)
{
RobotThread rt1=new RobotThread("thread1");
RobotThread rt2=new RobotThread("thread2");
RobotThread rt3=new RobotThread("thread3");
new Thread(rt1).start();
new Thread(rt2).start();
new Thread(rt3).start();
}
}
当前的:1,当前的线程Id:11当前线程的名称:thread1
当前的:1,当前的线程Id:13当前线程的名称:thread3
当前的:1,当前的线程Id:12当前线程的名称:thread2
当前的:2,当前的线程Id:11当前线程的名称:thread1
当前的:2,当前的线程Id:13当前线程的名称:thread3
当前的:3,当前的线程Id:13当前线程的名称:thread3
当前的:2,当前的线程Id:12当前线程的名称:thread2
当前的:3,当前的线程Id:11当前线程的名称:thread1
当前的:3,当前的线程Id:12当前线程的名称:thread2