程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java ??ThreadLocal??????

Java ??ThreadLocal??????

編輯:關於JAVA

Java ??ThreadLocal??????。本站提示廣大學習愛好者:(Java ??ThreadLocal??????)文章只能為提供參考,不一定能成為您想要的結果。以下是Java ??ThreadLocal??????正文


ThreadLocal????????????????????????????????????????ThreadLocal??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

??????????

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import com.sun.javafx.webkit.Accessor;

public class ThreadLocalTest {
 static class ThreadLocalVariableHolder {
  private static ThreadLocal<Integer> value = new ThreadLocal<Integer>() {
   private Random random = new Random();
   
   protected synchronized Integer initialValue() {
    return random.nextInt(10000);
   }
  };
  
  public static void increment() {
   value.set(value.get() + 1);
  }
  
  public static int get() {
   return value.get();
  }
 }
 
 static class Accessor implements Runnable{
  private final int id;
  
  public Accessor(int id) {
   this.id = id;
  }
  
  @Override
  public void run() {
   while (!Thread.currentThread().isInterrupted()) {
    ThreadLocalVariableHolder.increment();
    System.out.println(this);
    Thread.yield();
   }
  }
  
  @Override
  public String toString() {
   return "#" + id + ": " + ThreadLocalVariableHolder.get();
  }
  
 }
 
 public static void main(String[] args) {
  ExecutorService executorService = Executors.newCachedThreadPool();
  for (int i = 0; i < 5; i++) {
   executorService.execute(new Accessor(i));
  }
  try {
   TimeUnit.MICROSECONDS.sleep(1);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  executorService.shutdownNow();
 }

}

??????????

#1: 9685
#1: 9686
#2: 138
#2: 139
#2: 140
#2: 141
#0: 5255
??????

??????????????????????????????????Local??????????????????????????

ThreadLocal????????????????????????set,get??remove??

??Android ????Looper??????????ThreadLocal????????????????????????????Looper??????

public final class Looper {
 private static final String TAG = "Looper";

 // sThreadLocal.get() will return null unless you've called prepare().
 static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

 private static void prepare(boolean quitAllowed) {
  if (sThreadLocal.get() != null) {
   throw new RuntimeException("Only one Looper may be created per thread");
  }
  sThreadLocal.set(new Looper(quitAllowed));
 }
 
 ??????
}

????????????????????Looper????????????????????Looper.prepare()??????????????????????????Looper??????MessageQueue??????Looper??????????ThreadLocal????

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved