Multithreading
Multithreading
A technique for running multiple threads within a single process. Improves CPU utilization. Synchronization issues require care.
Multithreading
A technique for running multiple threads within a single process. Improves CPU utilization. Synchronization issues require care.
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.
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; }
}
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free