W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
線程局部變量分隔每個(gè)線程的變量的值。
java.lang包中的ThreadLocal類提供了一個(gè)線程局部變量的實(shí)現(xiàn)。
它有四個(gè)方法:get(),set(),remove()和initialValue()。
get()和set()方法分別用于獲取和設(shè)置線程局部變量的值。
您可以使用remove()方法刪除該值。
initialValue()方法設(shè)置變量的初始值,它具有受保護(hù)的訪問(wèn)。要使用它,子類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); } }
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: