線程局部變量分隔每個線程的變量的值。
java.lang包中的ThreadLocal類提供了一個線程局部變量的實現(xiàn)。
它有四個方法: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); } }
上面的代碼生成以下結果。
更多建議: