Java 병렬 프로그래밍의 ThreadLocal 클래스 인스턴스 설명

ThreadLocal 클래스는 ThreadLocalVariable (루트 국부 변수) 으로 이해할 수 있으며, get과 set 등 접근 인터페이스나 방법을 제공합니다. 이 방법은 이 변수를 사용하는 루트마다 독립된 복사본을 저장하기 때문에 get은 현재 실행 루트가 set를 호출할 때 설정한 최신 값을 되돌려줍니다.ThreadLocal를 맵 객체가 포함된 것으로 간주하여 해당 스레드에 지정된 값을 저장할 수 있습니다.
요약하면 다중 스레드 자원 공유의 문제에 대해 동기화 메커니즘은'시간으로 공간을 바꾼다'는 방식을 사용하고 ThreadLocal은'공간으로 시간을 바꾼다'는 방식을 사용했다.전자는 단지 하나의 변수만 제공하여 서로 다른 라인을 줄을 서서 방문하게 하고, 후자는 모든 라인에 하나의 변수를 제공하기 때문에 동시에 방문할 수 있어 서로 영향을 주지 않는다.
아날로그 ThreadLocal

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); // ②
  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

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();
 }
}
출력

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

좋은 웹페이지 즐겨찾기