99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

Java 線程局部變量

2018-02-28 16:12 更新

Java線程教程 - Java線程局部變量


線程局部變量分隔每個線程的變量的值。

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);
  }
}

上面的代碼生成以下結果。



以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號