Java 병렬 프로그래밍의 ThreadLocal 클래스 인스턴스 설명
3491 단어 Java동시 프로그래밍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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.