Java.lang.ThreadLocal.set() 方法
描述
java.lang.ThreadLocal.set() 方法将此线程局部变量的当前线程副本设置为指定值。
声明
以下是 java.lang.ThreadLocal.set() 方法的声明。
public void set(T value)
参数
value − 这是要存储在此线程本地的当前线程副本中的值。
返回值
此方法不返回任何值。
异常
NA
示例
下面的例子展示了 java.lang.ThreadLocal.set() 方法的使用。
package com.tutorialspoint; import java.lang.*; public class ThreadLocalDemo { public static void main(String[] args) { ThreadLocal<Integer> tlocal = new ThreadLocal<Integer>(); /* sets the current thread's copy of this thread-local variable to the specified value. */ tlocal.set(100); // returns the current thread's value of this thread-local System.out.println("value = " + tlocal.get()); tlocal.set(0); // returns the current thread's value of this thread-local System.out.println("value = " + tlocal.get()); } }
让我们编译并运行上面的程序,这将产生下面的结果 −
value = 100 value = 0