Java 线程局部变量

2018-02-28 16:12 更新

Java线程教程 - Java线程局部变量


线程局部变量分隔每个线程的变量的值。

java.lang包中的ThreadLocal类提供了一个线程局部变量的实现。

它有四个方法:get(),set(),remove()和initialValue()。

get()和set()方法分别用于获取和设置线程局部变量的值。

您可以使用remove()方法删除该值。

initialValue()方法设置变量的初始值,它具有受保护的访问。要使用它,子类ThreadLocal类并重写此方法。

例子

以下代码显示如何使用ThreadLocal类。

public class Main {
  public static void main(String[] args) {
    new Thread(Main::run).start();
    new Thread(Main::run).start();
  }
  public static void run() {
    int counter = 3;
    System.out.println(Thread.currentThread().getName()+ "  generated counter:  " + counter);
    for (int i = 0; i < counter; i++) {
      CallTracker.call();
    }
  }
}
class CallTracker {
  private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>();
  public static void call() {
    int counter = 0;
    Integer counterObject = threadLocal.get();

    if (counterObject == null) {
      counter = 1;
    } else {
      counter = counterObject.intValue();
      counter++;
    }
    threadLocal.set(counter);
    String threadName = Thread.currentThread().getName();
    System.out.println("Call  counter for " + threadName + "  = " + counter);
  }
}

上面的代码生成以下结果。



以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号