Java의 ThreadLocal 클래스 상세 정보

3021 단어 JavaThreadLocal
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에 저장합니다.

좋은 웹페이지 즐겨찾기