본문으로 건너뛰기
Advertisement

멀티 쓰레드 기초 (Thread & Runnable)

자바에서 멀티 쓰레딩(Multi-threading)은 여러 개의 작업을 동시에 수행할 수 있도록 해주는 아주 중요한 기술입니다. 하나의 프로세스 내에서 동시에 여러 개의 흐름(Thread)을 생성하여 병렬로 작업을 처리할 수 있습니다.

1. 쓰레드를 생성하는 방법

자바에서 쓰레드를 생성하는 방법은 크게 두 가지가 있습니다:

  1. Thread 클래스를 상속받는 방법
  2. Runnable 인터페이스를 구현하는 방법 (권장)

자바는 다중 상속을 지원하지 않기 때문에, 다른 클래스를 상속받아야 하는 경우를 대비해 Runnable 인터페이스를 구현하는 방법이 더 널리 사용됩니다.

Thread 클래스 상속

class MyThread extends Thread {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(getName() + " 실행 중"); // Thread 이름 출력
}
}
}

public class ThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();

t1.start(); // run()이 아닌 start()를 호출해야 새로운 쓰레드가 실행됨
t2.start();
}
}

Runnable 인터페이스 구현

class MyRunnable implements Runnable {
@Override
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " 실행 중");
}
}
}

public class RunnableExample {
public static void main(String[] args) {
Runnable r = new MyRunnable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);

t1.start();
t2.start();
}
}

주의점: run() 메서드를 직접 호출하면 단순히 클래스 내부의 메서드를 호출하는 것일 뿐이며, 새로운 쓰레드를 생성하여 실행하려면 반드시 start()를 호출해야 합니다.

2. 데몬 쓰레드 (Daemon Thread)

데몬 쓰레드는 일반 쓰레드(Main 쓰레드 등)의 작업을 돕는 보조적인 역할을 수행하는 쓰레드입니다. 대표적인 예로 가비지 컬렉터(Garbage Collector)나 자동 저장 기능 등이 있습니다. 일반 쓰레드가 모두 종료되면 데몬 쓰레드는 자동으로 종료됩니다.

public class DaemonThreadExample implements Runnable {
static boolean autoSave = false;

public static void main(String[] args) {
Thread t = new Thread(new DaemonThreadExample());
t.setDaemon(true); // 반드시 start() 호출 전에 데몬으로 설정해야 함
t.start();

for (int i = 1; i <= 10; i++) {
try { Thread.sleep(1000); } catch(InterruptedException e) {}
System.out.println(i);

if (i == 5) {
autoSave = true;
}
}
System.out.println("프로그램 종료");
}

@Override
public void run() {
while (true) {
try { Thread.sleep(3000); } catch(InterruptedException e) {}
if (autoSave) {
System.out.println("작업이 자동저장되었습니다.");
}
}
}
}

위 코드를 실행하면 Main 쓰레드가 10초 후에 종료되면서, 무한 루프를 도는 데몬 쓰레드도 함께 즉시 종료되는 것을 확인할 수 있습니다.

Advertisement