📜  Java并发-ThreadLocal类

📅  最后修改于: 2020-11-15 03:52:00             🧑  作者: Mango


ThreadLocal类用于创建只能由同一线程读取和写入的线程局部变量。例如,如果两个线程正在访问引用了相同threadLocal变量的代码,则每个线程将看不到其他线程对threadLocal变量所做的任何修改。

ThreadLocal方法

以下是ThreadLocal类中可用的重要方法的列表。

Sr.No. Method & Description
1

public T get()

Returns the value in the current thread’s copy of this thread-local variable.

2

protected T initialValue()

Returns the current thread’s “initial value” for this thread-local variable.

3

public void remove()

Removes the current thread’s value for this thread-local variable.

4

public void set(T value)

Sets the current thread’s copy of this thread-local variable to the specified value.

下面的TestThread程序演示了ThreadLocal类的其中一些方法。在这里,我们使用了两个计数器变量,一个是普通变量,另一个是ThreadLocal。

class RunnableDemo implements Runnable {
   int counter;
   ThreadLocal threadLocalCounter = new ThreadLocal();

   public void run() {     
      counter++;

      if(threadLocalCounter.get() != null) {
         threadLocalCounter.set(threadLocalCounter.get().intValue() + 1);
      } else {
         threadLocalCounter.set(0);
      }
      System.out.println("Counter: " + counter);
      System.out.println("threadLocalCounter: " + threadLocalCounter.get());
   }
}

public class TestThread {

   public static void main(String args[]) {
      RunnableDemo commonInstance = new RunnableDemo();

      Thread t1 = new Thread(commonInstance);
      Thread t2 = new Thread(commonInstance);
      Thread t3 = new Thread(commonInstance);
      Thread t4 = new Thread(commonInstance);

      t1.start();
      t2.start();
      t3.start();
      t4.start();

      // wait for threads to end
      try {
         t1.join();
         t2.join();
         t3.join();
         t4.join();
      } catch (Exception e) {
         System.out.println("Interrupted");
      }
   }
}

这将产生以下结果。

输出

Counter: 1
threadLocalCounter: 0
Counter: 2
threadLocalCounter: 0
Counter: 3
threadLocalCounter: 0
Counter: 4
threadLocalCounter: 0

您可以看到每个线程都增加了counter的值,但是每个线程的threadLocalCounter仍然为0。