多线程学习六——ThreadLocal的使用

package day1;

import java.util.HashMap;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

public class ThreadLocalTest {
    static CyclicBarrier c = new CyclicBarrier(2);
    private ThreadLocal<HashMap<String,String>> mapLocal = new ThreadLocal<HashMap<String,String>>(){
        @Override
        protected HashMap<String,String> initialValue() {
            return new HashMap<String,String>();
        }
    };
    private HashMap<String,String> hashMap= new HashMap<String,String>();
    public void put(String key,String value) {
        HashMap<String,String> hashMap = mapLocal.get();
        if(hashMap == null) {
            System.out.println("=======");
            hashMap = new HashMap<String,String>();
        }
        hashMap.put(key, value);
        mapLocal.set(hashMap);
    }
    public String get(String key) {
        return mapLocal.get().get(key);
    }

    public HashMap<String, String> getHashMap() {
        return hashMap;
    }
    public void setHashMap(HashMap<String, String> hashMap) {
        this.hashMap = hashMap;
    }
    public static void main(String[] args) throws Exception {
        ThreadLocalTest profiler=new ThreadLocalTest();
        for(int i =0;i<6;i++) {
            new Thread("thread"+i) {
                public void run() {
                    try {
                        c.await();
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (BrokenBarrierException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    profiler.put("name", Thread.currentThread().getName());
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        System.out.println(Thread.currentThread().getName()+":"
                                +profiler.get("name"));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        for(int i =6;i<12;i++) {
            new Thread("thread"+i) {
                public void run() {
                    try {
                        c.await();
                    } catch (InterruptedException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    } catch (BrokenBarrierException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    profiler.getHashMap().put("name", Thread.currentThread().getName());
                        System.out.println(Thread.currentThread().getName()+":"
                                +profiler.getHashMap().get("name"));

                }
            }.start();
        }
    }
}

console输出:

thread8:thread9
thread9:thread9
thread6:thread11
thread10:thread11
thread11:thread11
thread0:thread0
thread1:thread1
thread2:thread2
thread4:thread4
thread3:thread3
thread7:thread7
thread5:thread5

线程0-5中的name的值跟线程名是一一对应的,6-11则每次运行的时候都会不一样,所以ThreadLocal可用于保证线程安全,每个线程都保有一个ThreadLocal

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在多线程环境中,我们可以使用ThreadLocal类来实现线程局部变量。ThreadLocal为每个线程提供了一个独立的存储空间,每个线程都可以独立地修改自己的副本,互不干扰。 要在多线程环境中使用ThreadLocal,我们需要执行以下步骤: 1. 创建ThreadLocal对象:通过创建ThreadLocal对象来保存线程的局部变量。例如,可以使用`ThreadLocal<Integer>`来保存一个整数类型的线程局部变量。 2. 设置线程局部变量:在每个线程中,通过调用ThreadLocal对象的`set()`方法来设置该线程的局部变量的值。例如,使用`threadLocal.set(value)`来设置线程局部变量的值为value。 3. 获取线程局部变量:在每个线程中,通过调用ThreadLocal对象的`get()`方法来获取该线程的局部变量的值。例如,使用`threadLocal.get()`来获取线程局部变量的值。 4. 移除线程局部变量(可选):如果需要,在每个线程结束时,可以通过调用ThreadLocal对象的`remove()`方法来移除该线程的局部变量。例如,使用`threadLocal.remove()`来移除线程局部变量。 下面是一个示例代码,演示如何在多线程环境中使用ThreadLocal: ```java public class ThreadLocalExample { private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(); public static void main(String[] args) { Thread thread1 = new Thread(() -> { threadLocal.set(1); System.out.println("Thread 1: " + threadLocal.get()); threadLocal.remove(); }); Thread thread2 = new Thread(() -> { threadLocal.set(2); System.out.println("Thread 2: " + threadLocal.get()); threadLocal.remove(); }); thread1.start(); thread2.start(); } } ``` 这个示例中,我们创建了一个ThreadLocal对象来保存整数类型的线程局部变量。在每个线程中,我们使用`threadLocal.set()`方法来设置线程局部变量的值,并使用`threadLocal.get()`方法来获取线程局部变量的值。最后,我们调用`threadLocal.remove()`方法来移除线程局部变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值