java里ThreadLocal的使用

ThreadLocal的作用:
使变量在每个线程独立

ThreadLocal的使用:

ThreadLocal threadLocal = new ThreadLocal<>(); //创建ThreadLocal对象(有泛型,多个对象创建多个ThreadLocal对象)
threadLocal.set(T t); //设置变量 T temp = threadLocal.get();//读取变量
threadLocal.remove(); //释放资源,防止内存泄漏

例:
没有使用ThreadLocal

public class MyRunnable implements Runnable{

    private Integer id = 0;

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我是 "+Thread.currentThread().getName()+" 的id: "+(++id));
        }

    }

}
public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    for (int i = 0; i < 50; i++) {
        new Thread(myRunnable).start();
    }
}

结果:

我是 Thread-0 的id: 1
我是 Thread-0 的id: 2
我是 Thread-0 的id: 3
我是 Thread-0 的id: 4
...
我是 Thread-20 的id: 4993
我是 Thread-20 的id: 4994
我是 Thread-20 的id: 4995
我是 Thread-20 的id: 4996
我是 Thread-15 的id: 4984
我是 Thread-15 的id: 4997
我是 Thread-15 的id: 4998

Process finished with exit code 0

使用ThreadLocal

public class MyRunnable implements Runnable{

    private Integer id = 0;

    @Override
    public void run() {
        ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        threadLocal.set(id);
        for (int i = 0; i < 100; i++) {
            Integer temp = threadLocal.get();
            System.out.println("我是 "+Thread.currentThread().getName()+" 的id: "+(++temp));
            threadLocal.set(temp);
        }
        threadLocal.remove();//释放资源
    }

}
public static void main(String[] args) {
    MyRunnable myRunnable = new MyRunnable();
    for (int i = 0; i < 50; i++) {
        new Thread(myRunnable).start();
    }
}

结果:

我是 Thread-1 的id: 1
我是 Thread-1 的id: 2
我是 Thread-1 的id: 3
我是 Thread-1 的id: 4
我是 Thread-1 的id: 5
我是 Thread-1 的id: 6
...
我是 Thread-19 的id: 94
我是 Thread-19 的id: 95
我是 Thread-19 的id: 96
我是 Thread-19 的id: 97
我是 Thread-19 的id: 98
我是 Thread-19 的id: 99
我是 Thread-19 的id: 100

Process finished with exit code 0
posted @ 2022-03-07 18:04  叕叕666  阅读(80)  评论(0)    收藏  举报