スレッドのThreadLocalクラス

序文

ここに画像の説明を挿入

ThreadLocalには分離があります

/**
 * 验证ThreadLocal隔离性
 * @author layman
 */
public class Demo17 {
    
    
    public static void main(String[] args) {
    
    
        ThreadLocal<String> threadLocal = new ThreadLocal<>();
        Demo17ThreadA threadA = new Demo17ThreadA(threadLocal);
        threadA.setName("线程A");
        threadA.start();
        
        Demo17ThreadA threadB = new Demo17ThreadA(threadLocal);
        threadB.setName("线程B");
        threadB.start();
    }
}
class Demo17ThreadA extends Thread{
    
    
    private ThreadLocal<String> threadLocal;
    public Demo17ThreadA(ThreadLocal<String> threadLocal){
    
    
        this.threadLocal = threadLocal;
    }
    @SneakyThrows
    @Override
    public void run() {
    
    
        for (int i = 0; i < 10; i++) {
    
    
            threadLocal.set(Thread.currentThread().getName() + "第"+(i+1)+"个值");
            System.out.println(threadLocal.get());
            Thread.sleep(500);
        }
    }
}

運転結果

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/single_0910/article/details/113769466