Java ThreadLocal基本原理及运用

java

ThreadLocal提供本地线程变量。这个变量里面的值(通过get方法获取)是和其他线程分割开来的,变量的值只有当前线程能访问到,不像一般的类型比如Person,Student类型的变量,只要访问到声明该变量的对象,即可访问其全部内容,而且各个线程的访问的数据是无差别的。

static ThreadLocal<String> stringThreadLocal = new ThreadLocal<>();

@Test

public void test01(){

Thread thread1 = new Thread(){

@Override

public void run() {

stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());

System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());

}

};

Thread thread2 = new Thread(){

@Override

public void run() {

stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());

System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());

}

};

Thread thread3 = new Thread(){

@Override

public void run() {

stringThreadLocal.set("threadName===>"+Thread.currentThread().getName());

System.out.println(this.getName()+" thread get the value:"+stringThreadLocal.get());

}

};

thread1.start();

thread2.start();

thread3.start();

System.out.println("main线程调用set方法之前:"+stringThreadLocal.get());

stringThreadLocal.set("main 线程set的值");

System.out.println("main线程调用set方法之后:"+stringThreadLocal.get());

}

功能就是往线程里传值。

以上是 Java ThreadLocal基本原理及运用 的全部内容, 来源链接: utcz.com/z/390764.html

回到顶部