💻 Programming

Multithreading

Multithreading

A technique for running multiple threads within a single process. Improves CPU utilization. Synchronization issues require care.

📖 Detailed Explanation

Multithreading is a programming technique that executes multiple threads simultaneously within a single process. Each thread has its own independent flow of execution while sharing the process's memory and resources.

The advantages of multithreading are improved CPU utilization, better responsiveness, and efficient resource sharing. Separating the UI thread from background threads keeps the UI from freezing even during long-running tasks.

However, multithreading entails synchronization problems. When multiple threads access the same data, problems such as race conditions, deadlocks, and livelocks can occur. These are resolved with synchronization techniques such as mutexes, semaphores, and monitors.

Because of the GIL (Global Interpreter Lock), true parallel execution is difficult for CPU-bound tasks in Python. Java, C++, Rust, and others support native multithreading, while Go provides a lighter-weight concurrency model with goroutines.

💻 Code Example

Java
import java.util.concurrent.*;

public class MultithreadingExample {
    public static void main(String[] args) throws Exception {
        // 1. Thread 클래스 상속
        Thread thread1 = new Thread(() -> {
            System.out.println("스레드 1: " + Thread.currentThread().getName());
        });
        thread1.start();

        // 2. 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());
            });
        }

        executor.shutdown();
        executor.awaitTermination(1, TimeUnit.MINUTES);

        // 3. 동기화가 필요한 경우
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> { for(int i=0; i<1000; i++) counter.increment(); });
        Thread t2 = new Thread(() -> { for(int i=0; i<1000; i++) counter.increment(); });
        t1.start(); t2.start();
        t1.join(); t2.join();
        System.out.println("카운터: " + counter.getCount()); // 2000
    }
}

class Counter {
    private int count = 0;
    public synchronized void increment() { count++; }
    public int getCount() { return count; }
}

🗣️ Examples of Practical Conversations

Backend developer
"The image processing task is blocking the main thread, so API responses are slow."
Senior developer
"Use a thread pool to move the image processing to the background. After the task completes, you can send a notification via a callback or an event."
Backend developer
"How should we determine the pool size? Based on the number of CPU cores?"
Interviewer
"Please explain the conditions under which a deadlock occurs and how to resolve it."
Candidate
"A deadlock occurs when all four conditions are met: mutual exclusion, hold and wait, no preemption, and circular wait. It is resolved by acquiring locks in a consistent order, setting a timeout, or using tryLock."
Interviewer
"How do I determine the appropriate size of a thread pool?"
Candidate
"For CPU-bound tasks, about the number of cores is typical; for I/O-bound tasks, two or more times the number of cores is typical. In practice, you should find the optimal value through load testing."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

Reviewer
"This HashMap is being accessed from multiple threads, so we should use ConcurrentHashMap or add synchronization."
Author
"I'll replace it with ConcurrentHashMap. Performance should be better too."
Reviewer
"And there's also a check-then-act pattern. Another thread can step in between the check and the action."

⚠️ Cautions

🔗 Related Terms

📚 Learn More