ThreadLocal自理解

版权声明:嘻嘻嘻嘻,I see you https://blog.csdn.net/qq_38317309/article/details/85718879
class Message{
 private String note;
 public void setNote(String note) {
  this.note = note;
 }
 public String getNote() {
  return note;
 }
}
class MessageConsumer{
 public void print(Message msg) {// Consumer 必须明确接收 Message类的对象
  System.out.println(Thread.currentThread().getName()+"="+MyUtil.get().getNote());
 }
}
class MyUtil{
 private static ThreadLocal<Message> threadLocal =new ThreadLocal<Message>();
 public static void set(Message msg) {
  threadLocal.set(msg);
 }
 public static Message get() {
  return threadLocal.get();
 }
}
public class TestDemo{
 public static void main(String[] args) throws Exception{
  new Thread(()-> {
   Message msg=new Message();
   msg.setNote("hello");
   MyUtil.set(msg);
   new MessageConsumer().print(msg);},"user1").start();
   
  new Thread(()-> {
   Message msg=new Message();
   msg.setNote("Morrnig");
   MyUtil.set(msg);
   new MessageConsumer().print(msg);},"User2").start();
 }
}

这是在MLDN上敲下来的代码,具体实现的是将USER1与USER2 的线程区分开,做到User1 绑定输出Hello,User2绑定输出Morning,关于ThreadLocal 的一些学习笔记如下
ThreadLocal 用于保存某个线程共享变量,在例子中,User1和User2都是利用的msg 作为变量名称的,也即共享变量名称。对于同一个Static ThreadLocal 不同线程只能从set、get、remove中获取自己的变量,而且不影响其他的线程,
set 的作用是设置当前线程共享变量的值,get即获取共享变量的值,remove 为移除。
在共性变量
Thread.Threadlocal<ThreadLocal,Object>;
Thread 表示当前线程, ThreadLocal 是Static ThreadLocal变量。 Object(Message)是为当前进程的共享变量。可以根据当期的ThreadLocal获取当前线程共享变量Object
总的来说ThreadLocal为每一个线程提供了一个变量副本,保证同一时间内只有一个线程去访问数据。

猜你喜欢

转载自blog.csdn.net/qq_38317309/article/details/85718879