Thread
Thread
A unit of execution within a process. Shares memory. A basis of concurrency.
Thread
A unit of execution within a process. Shares memory. A basis of concurrency.
A thread is the smallest unit of execution within a process. A process has at least one thread (the main thread), and can create multiple threads as needed to perform tasks concurrently. Threads share the process's code, data, and heap areas, but each has its own independent stack and registers. Because of these characteristics, communication between threads is faster and more efficient than inter-process communication (IPC).
The key difference between a process and a thread is whether memory is shared. Processes have independent memory spaces and therefore cannot access each other directly, but threads within the same process share heap memory. Creating a process requires copying the entire memory and is costly, whereas creating a thread only requires allocating a stack, so it is relatively lightweight. However, because memory is shared, an error in one thread can affect the entire process.
The advantages of multithreading are maximized CPU utilization, improved responsiveness, and efficient resource sharing. In a single thread, the CPU sits idle during I/O wait time, but in multithreading, another thread can use the CPU. However, the disadvantages are also clear. Synchronization problems (Race Condition), deadlock, difficulty in debugging, and context switching overhead can occur. If the number of threads is excessive, performance actually degrades.
In practice, threads are used as a core tool for parallel processing and asynchronous tasks. Web servers allocate a thread to each request to handle requests concurrently, and GUI applications keep themselves responsive by separating the UI thread from worker threads. Recently, thread pools (Thread Pool) are used to reduce the cost of thread creation and destruction, and threads are managed with high-level APIs such as Java's ExecutorService and Python's ThreadPoolExecutor. In addition, the async/await pattern and coroutines are replacing threads in many cases.
// Java Thread 예제 - 다양한 스레드 생성 및 동기화
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
public class ThreadExample {
// 1. Thread 클래스 상속
static class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
// 2. Runnable 인터페이스 구현 (권장)
static class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name + " 실행 중 - " +
Thread.currentThread().getName());
}
}
// 3. 동기화 예제 - synchronized
static class Counter {
private int count = 0;
// synchronized 메서드
public synchronized void increment() {
count++;
}
// synchronized 블록
public void incrementWithBlock() {
synchronized(this) {
count++;
}
}
public int getCount() {
return count;
}
}
// 4. ReentrantLock 사용
static class SafeCounter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock(); // 반드시 finally에서 해제
}
}
public int getCount() {
return count;
}
}
public static void main(String[] args) throws Exception {
// Thread 클래스 사용
MyThread t1 = new MyThread("Thread-1");
t1.start();
// Runnable 사용
Thread t2 = new Thread(new MyRunnable("Runnable-1"));
t2.start();
// Lambda 표현식 (Java 8+)
Thread t3 = new Thread(() -> {
System.out.println("Lambda Thread 실행");
});
t3.start();
// ExecutorService - 스레드 풀 (권장)
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
final int taskId = i;
executor.submit(() -> {
System.out.println("Task " + taskId + " - " +
Thread.currentThread().getName());
});
}
// Future를 통한 결과 받기
Future future = executor.submit(() -> {
Thread.sleep(1000);
return 42;
});
System.out.println("결과: " + future.get()); // 블로킹
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
// CompletableFuture (Java 8+, 비동기 체이닝)
CompletableFuture.supplyAsync(() -> "Hello")
.thenApply(s -> s + " World")
.thenAccept(System.out::println)
.join();
}
}
# Python threading 예제 - 스레드 생성 및 동기화
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from queue import Queue
# 1. 기본 스레드 생성 - Thread 클래스
def worker(name: str, delay: float) -> None:
"""작업 함수"""
print(f"{name} 시작")
time.sleep(delay)
print(f"{name} 완료")
# 함수 기반 스레드
t1 = threading.Thread(target=worker, args=("Worker-1", 1))
t1.start()
t1.join() # 스레드 종료 대기
# 2. Thread 클래스 상속
class MyThread(threading.Thread):
def __init__(self, name: str):
super().__init__()
self.name = name
self.result = None
def run(self):
print(f"{self.name} 실행 중")
time.sleep(0.5)
self.result = f"{self.name} 결과"
thread = MyThread("Custom-Thread")
thread.start()
thread.join()
print(thread.result)
# 3. 동기화 - Lock
counter = 0
lock = threading.Lock()
def increment_with_lock():
global counter
for _ in range(100000):
with lock: # context manager 사용 권장
counter += 1
threads = [threading.Thread(target=increment_with_lock) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(f"Counter: {counter}") # 400000
# 4. RLock (재진입 가능한 락)
rlock = threading.RLock()
def recursive_function(n: int):
with rlock:
if n > 0:
print(f"Level {n}")
recursive_function(n - 1)
# 5. Condition - 스레드 간 신호
condition = threading.Condition()
items = []
def producer():
for i in range(5):
with condition:
items.append(i)
print(f"Produced: {i}")
condition.notify() # 대기 중인 스레드 깨우기
time.sleep(0.1)
def consumer():
for _ in range(5):
with condition:
while not items:
condition.wait() # 신호 대기
item = items.pop(0)
print(f"Consumed: {item}")
# 6. ThreadPoolExecutor (권장)
def fetch_url(url: str) -> dict:
"""URL 데이터 가져오기 시뮬레이션"""
time.sleep(0.5) # 네트워크 지연 시뮬레이션
return {"url": url, "status": 200}
urls = [f"https://api.example.com/{i}" for i in range(10)]
with ThreadPoolExecutor(max_workers=4) as executor:
# submit으로 개별 제출
futures = {executor.submit(fetch_url, url): url for url in urls}
for future in as_completed(futures):
url = futures[future]
try:
result = future.result()
print(f"{url}: {result['status']}")
except Exception as e:
print(f"{url} 실패: {e}")
# 7. Queue를 이용한 생산자-소비자 패턴
task_queue = Queue()
def queue_producer():
for i in range(10):
task_queue.put(f"Task-{i}")
task_queue.put(None) # 종료 신호
def queue_consumer():
while True:
task = task_queue.get()
if task is None:
break
print(f"Processing: {task}")
task_queue.task_done()
# 8. daemon 스레드 - 메인 종료 시 자동 종료
daemon_thread = threading.Thread(target=worker, args=("Daemon", 10))
daemon_thread.daemon = True # 데몬 스레드 설정
daemon_thread.start()
# 메인 종료 시 데몬 스레드도 종료됨
# 9. 현재 스레드 정보
print(f"현재 스레드: {threading.current_thread().name}")
print(f"활성 스레드 수: {threading.active_count()}")
"There are several ways to synchronize threads. The most basic is mutual exclusion using the synchronized keyword or a Lock. However, for a simple counter, atomic operations such as AtomicInteger are more efficient, and when reads are frequent, you use ReentrantReadWriteLock. Since Java 21, Virtual Thread has been introduced, making lightweight concurrency handling possible, and if you use ReentrantLock instead of synchronized, fine-grained control such as timeouts, interrupts, and fairness settings becomes possible."
"The server was unresponsive, so I took a thread dump with jstack, and a deadlock was found. It's a situation where Thread-1 holds Lock-A and waits for Lock-B, while Thread-2 holds Lock-B and waits for Lock-A. As a solution, we should define a consistent lock acquisition order, set a timeout with tryLock, and, where possible, reduce the scope of the lock to minimize holding time. In the long term, I think we should consider adopting lock-free data structures or a message queue pattern."
"The thread pool size is set to 10 times the number of CPU cores. You need to check whether this task is CPU-bound or I/O-bound. If it's CPU-bound, about the number of cores is appropriate, and if it's I/O-bound, you can increase it further depending on the wait-time ratio. Also, instead of Executors.newFixedThreadPool, it's safer in production to create a ThreadPoolExecutor directly and specify the queue size and rejection policy explicitly."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
A problem where the result varies depending on execution order when multiple threads access a shared resource simultaneously. It occurs when a read-modify-write operation is not atomic. Resolve it with synchronized, Lock, or Atomic classes. However, excessive synchronization causes performance degradation and deadlocks.
A state in which two or more threads wait indefinitely for locks held by each other. To prevent it: 1) maintain a consistent lock acquisition order, 2) set a timeout with tryLock, 3) minimize lock holding time, 4) use deadlock detection tools. You can diagnose deadlocks by analyzing thread dumps with jstack and VisualVM.
Creating threads without limit causes performance to plummet due to memory exhaustion and context switching overhead. Always use a thread pool and set an appropriate size. For CPU-bound tasks, the guideline is the number of cores; for I/O-bound tasks, it is number of cores * (1 + wait time/task time). Also set the queue size and rejection policy explicitly.
A problem where a value changed by one thread is not seen by another thread. It occurs because of CPU caches and compiler optimizations. In Java, the volatile keyword guarantees visibility, and Python's GIL provides some protection, but explicit synchronization is recommended. It is important to understand the happens-before relationship.