多线程ThreadLocal

多线程ThreadLocal用法

public class Tools {

    public static ThreadLocal t1 = new ThreadLocal();
`
}``

@Slf4j
public class ThreadA implements Runnable{
@Override
public void run() {
try{
for(int i=0;i<5;i++){
Tools.t1.set(“ThreadA=”+(i+1));
log.info(“ThreadA get vaule”+Tools.t1.get());
Thread.sleep(200);
}
}catch (Exception e){
}
}
}


@Slf4j
public class ThreadB implements Runnable{
@Override
public void run() {
try{
for(int i=5;i<10;i++){
Tools.t1.set(“ThreadB=”+(i+1));
log.info(“ThreadB get vaule”+Tools.t1.get());
Thread.sleep(200);
}

    }catch (Exception e){

    }
}

}


public static void main(String[] args) {

   Thread a = new Thread( new ThreadA());
  Thread b = new Thread( new ThreadB());

  a.start();
    b.start();
    }

线程A和线程B的 threadlocal变量互不影响,线程独有变量

你可能感兴趣的:(多线程,ThreadLocal,多线程,thread,java)