Threadlocal

상훈·2024년 1월 30일

스레드 간에 데이터를 궁유하지 않고 스레드 내부에서 데이터를 유지하고 싶을 때 사용되는 클래스

  • 싱글톤 패턴을 사용할 때 주로 나타나는 동시성 문제를 해결 할 수 있음
  1. 스레드 간의 데이터 격리 : 스레드는 자체적으로 'ThreadLocal' 변수에 액세스함 -> 다른 스레드의 변수에 영향을 미치지 않음
  2. 스레드 안정성 : 변수는 스레드 간에 공유되지 않음
public class MyThreadLocalExample {

    // ThreadLocal 변수 생성
    private static ThreadLocal<String> threadLocalVariable = new ThreadLocal<>();

    public static void main(String[] args) {
        // 첫 번째 스레드에서 변수 설정
        Thread thread1 = new Thread(() -> {
            threadLocalVariable.set("Value set by Thread 1");
            printVariable("Thread 1");
        });

        // 두 번째 스레드에서 변수 설정
        Thread thread2 = new Thread(() -> {
            threadLocalVariable.set("Value set by Thread 2");
            printVariable("Thread 2");
        });

        // 각 스레드 시작
        thread1.start();
        thread2.start();
    }

    private static void printVariable(String threadName) {
        // 스레드별로 설정된 변수 출력
        System.out.println(threadName + " - Variable Value: " + threadLocalVariable.get());
    }
}

profile
문송 개발자

0개의 댓글