Java ThreadLocal get() 方法



描述

Java ThreadLocal get() 方法返回当前线程在此线程局部变量的副本中的值。

声明

以下是 java.lang.ThreadLocal.get() 方法的声明

public T get()

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

参数

返回值

此方法返回此线程局部的当前线程的值。

异常

示例:从 ThreadLocal 对象获取整数值

以下示例演示了 Java ThreadLocal get() 方法的用法。在此程序中,我们初始化了一个 ThreadLocal 对象。使用 set() 方法,将值分配给 ThreadLocal 对象,并使用 get() 方法检索并打印值。使用新值重复相同的过程,并打印结果。

Open Compiler
package com.tutorialspoint; public class ThreadLocalDemo { public static void main(String[] args) { ThreadLocal<Integer> tlocal = new ThreadLocal<>(); tlocal.set(100); // returns the current thread's value System.out.println("value = " + tlocal.get()); tlocal.set(90); // returns the current thread's value of System.out.println("value = " + tlocal.get()); } }

输出

让我们编译并运行以上程序,这将产生以下结果:

value = 100
value = 90

示例:从 ThreadLocal 对象获取双精度值

以下示例演示了 Java ThreadLocal get() 方法的用法。在此程序中,我们初始化了一个 ThreadLocal 对象。使用 set() 方法,将值分配给 ThreadLocal 对象,并使用 get() 方法检索并打印值。使用新值重复相同的过程,并打印结果。

Open Compiler
package com.tutorialspoint; public class ThreadLocalDemo { public static void main(String[] args) { ThreadLocal<Double> tlocal = new ThreadLocal<>(); tlocal.set(100.0); // returns the current thread's value System.out.println("value = " + tlocal.get()); tlocal.set(90.0); // returns the current thread's value of System.out.println("value = " + tlocal.get()); } }

输出

让我们编译并运行以上程序,这将产生以下结果:

value = 100.0
value = 90.0

示例:从 ThreadLocal 对象获取字符串值

以下示例演示了 Java ThreadLocal get() 方法的用法。在此程序中,我们初始化了一个 ThreadLocal 对象。使用 set() 方法,将值分配给 ThreadLocal 对象,并使用 get() 方法检索并打印值。使用新值重复相同的过程,并打印结果。

Open Compiler
package com.tutorialspoint; public class ThreadLocalDemo { public static void main(String[] args) { ThreadLocal<String> tlocal = new ThreadLocal<>(); tlocal.set("100"); // returns the current thread's value System.out.println("value = " + tlocal.get()); tlocal.set("90"); // returns the current thread's value of System.out.println("value = " + tlocal.get()); } }

输出

让我们编译并运行以上程序,这将产生以下结果:

value = 100
value = 90
java_lang_threadlocal.htm
广告