奶头挺立呻吟高潮av全片,成人试看120秒体验区,性欧美极品v,A片高潮抽搐揉捏奶头视频

java語言

Java并發(fā)編程:深入剖析ThreadLocal

時間:2025-03-15 23:04:02 java語言 我要投稿
  • 相關(guān)推薦

Java并發(fā)編程:深入剖析ThreadLocal

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

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

  模擬ThreadLocal

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

  import java.util.Collections;

  import java.util.HashMap;

  import java.util.Map;

  public class SimpleThreadLocal{

  private MapvalueMap = Collections

  .synchronizedMap(new HashMap());

  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 SimpleThreadLocalcount = new SimpleThreadLocal() {

  @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

  + "tht" + 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

【Java并發(fā)編程:深入剖析ThreadLocal】相關(guān)文章:

java并發(fā)編程參考10-30

簡單地分析Java線程編程中ThreadLocal類的使用08-10

java編程術(shù)語11-10

java編程基礎(chǔ)07-26

Java編程語言10-02

Java中同步與并發(fā)的運用07-31

java教程之Java編程基礎(chǔ)09-12

Java編程環(huán)境的搭建06-03

java編程規(guī)范介紹07-10

主站蜘蛛池模板: 井冈山市| 巴林右旗| 天等县| 西华县| 红桥区| 邵阳县| 积石山| 宣恩县| 威远县| 静海县| 苏尼特左旗| 丹凤县| 阿瓦提县| 穆棱市| 晋江市| 滦平县| 德惠市| 老河口市| 焦作市| 定安县| 普兰店市| 施甸县| 全南县| 南和县| 宜章县| 大城县| 四会市| 新晃| 汉川市| 台江县| 南投县| 中西区| 曲周县| 淳化县| 沧州市| 阳江市| 大同县| 竹溪县| 乐清市| 永年县| 余干县|