国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

實例講解Java并發(fā)編程之ThreadLocal類

2019-11-26 15:13:17
字體:
供稿:網(wǎng)友

ThreadLocal類可以理解為ThreadLocalVariable(線程局部變量),提供了get與set等訪問接口或方法,這些方法為每個使用該變量的線程都存有一份獨立的副本,因此get總是返回當(dāng)前執(zhí)行線程在調(diào)用set時設(shè)置的最新值。可以將ThreadLocal<T>視為 包含了Map<Thread,T>對象,保存了特定于該線程的值。

概括起來說,對于多線程資源共享的問題,同步機制采用了“以時間換空間”的方式,而ThreadLocal采用了“以空間換時間”的方式。前者僅提供一份變量,讓不同的線程排隊訪問,而后者為每一個線程都提供了一份變量,因此可以同時訪問而互不影響。

模擬ThreadLocal

復(fù)制代碼 代碼如下:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
public class SimpleThreadLocal<T> {
 private Map<Thread, T> valueMap = Collections
   .synchronizedMap(new HashMap<Thread, T>());
 
 public void set(T newValue) {
  valueMap.put(Thread.currentThread(), newValue); // ①鍵為線程對象,值為本線程的變量副本
 }
 
 public T get() {
  Thread currentThread = Thread.currentThread();
  T o = valueMap.get(currentThread); // ②返回本線程對應(yīng)的變量
  if (o == null && !valueMap.containsKey(currentThread)) { // ③如果在Map中不存在,放到Map中保存起來。
   o = initialValue();
   valueMap.put(currentThread, o);
  }
  return o;
 }
 
 public void remove() {
  valueMap.remove(Thread.currentThread());
 }
 
 protected T initialValue() {
  return null;
 }
}

實用ThreadLocal
復(fù)制代碼 代碼如下:

class Count {
 private SimpleThreadLocal<Integer> count = new SimpleThreadLocal<Integer>() {
  @Override
  protected Integer initialValue() {
   return 0;
  }
 };
 
 public Integer increase() {
  count.set(count.get() + 1);
  return count.get();
 }
 
}
 
class TestThread implements Runnable {
 private Count count;
 
 public TestThread(Count count) {
  this.count = count;
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  for (int i = 1; i <= 3; i++) {
   System.out.println(Thread.currentThread().getName() + "/t" + i
     + "th/t" + count.increase());
  }
 }
}
 
public class TestThreadLocal {
 public static void main(String[] args) {
  Count count = new Count();
  Thread t1 = new Thread(new TestThread(count));
  Thread t2 = new Thread(new TestThread(count));
  Thread t3 = new Thread(new TestThread(count));
  Thread t4 = new Thread(new TestThread(count));
  t1.start();
  t2.start();
  t3.start();
  t4.start();
 }
}

輸出
復(fù)制代碼 代碼如下:

Thread-0    1th    1
Thread-0    2th    2
Thread-0    3th    3
Thread-3    1th    1
Thread-1    1th    1
Thread-1    2th    2
Thread-2    1th    1
Thread-1    3th    3
Thread-3    2th    2
Thread-3    3th    3
Thread-2    2th    2
Thread-2    3th    3

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 松溪县| 玉屏| 铁岭县| 镇赉县| 芦山县| 阳新县| 文昌市| 库伦旗| 台南县| 武清区| 雅江县| 九寨沟县| 甘谷县| 聂拉木县| 尉犁县| 白银市| 新龙县| 石阡县| 建水县| 田林县| 边坝县| 博野县| 乌苏市| 吴江市| 来安县| 且末县| 安阳县| 岱山县| 县级市| 仪征市| 贵州省| 鹿泉市| 万荣县| 赤壁市| 沁阳市| 富阳市| 南宫市| 平和县| 遂平县| 玉树县| 收藏|