✅ 자바에서 여러 개의 스레드를 순차적으로 실행하는 방법
자바에서 여러 개의 스레드를 순차적으로 실행할 수 있는 방법은 여러 가지가 있습니다.
자바의 기본 스레드 모델은 병렬 실행(Concurrent Execution) 을 목적으로 하지만,
적절한 동기화(Synchronization) 기법을 사용하면 순차 실행(Sequential Execution) 이 가능합니다.
🚀 1. join()을 사용하여 순차 실행
스레드의 join() 메서드를 사용하면 앞선 스레드가 끝날 때까지 기다린 후 다음 스레드를 실행할 수 있습니다.
📌 예제: join()을 이용한 순차 실행
class MyThread extends Thread {
private final String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name + " 실행 중...");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println(name + " 완료!");
}
}
public class ThreadJoinExample {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new MyThread("스레드 1");
Thread t2 = new MyThread("스레드 2");
Thread t3 = new MyThread("스레드 3");
t1.start();
t1.join(); // t1이 끝날 때까지 대기
t2.start();
t2.join(); // t2가 끝날 때까지 대기
t3.start();
t3.join(); // t3가 끝날 때까지 대기
System.out.println("모든 스레드 완료!");
}
}
✔ join()을 사용하면 t1이 끝나야 t2가 실행되고, t2가 끝나야 t3가 실행됨
✔ 모든 스레드가 순차적으로 실행됨
🛠 출력 결과
스레드 1 실행 중...
스레드 1 완료!
스레드 2 실행 중...
스레드 2 완료!
스레드 3 실행 중...
스레드 3 완료!
모든 스레드 완료!
⚡ 2. ExecutorService + SingleThreadExecutor 사용
ExecutorService에서 싱글 스레드 풀을 사용하면 자동으로 스레드가 순차적으로 실행됩니다.
📌 예제: ExecutorService 이용
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadExecutorExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor(); // 하나의 스레드만 실행
executor.submit(() -> {
System.out.println("작업 1 실행");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("작업 1 완료");
});
executor.submit(() -> {
System.out.println("작업 2 실행");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("작업 2 완료");
});
executor.submit(() -> {
System.out.println("작업 3 실행");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("작업 3 완료");
});
executor.shutdown(); // 작업 완료 후 종료
}
}
✔ Executors.newSingleThreadExecutor()를 사용하면 한 번에 하나의 스레드만 실행되도록 보장됨
✔ 스레드가 끝나야 다음 스레드가 실행되므로 자동으로 순차 실행됨
🛠 출력 결과
작업 1 실행
작업 1 완료
작업 2 실행
작업 2 완료
작업 3 실행
작업 3 완료
🎯 3. CountDownLatch를 사용하여 순차 실행
CountDownLatch는 일정 개수의 스레드가 완료될 때까지 대기하는 동기화 기법입니다.
📌 예제: CountDownLatch 이용
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch1 = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
Thread t1 = new Thread(() -> {
System.out.println("스레드 1 실행");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("스레드 1 완료");
latch1.countDown(); // latch1 감소 (t2가 실행 가능)
});
Thread t2 = new Thread(() -> {
try { latch1.await(); } catch (InterruptedException e) {}
System.out.println("스레드 2 실행");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("스레드 2 완료");
latch2.countDown(); // latch2 감소 (t3가 실행 가능)
});
Thread t3 = new Thread(() -> {
try { latch2.await(); } catch (InterruptedException e) {}
System.out.println("스레드 3 실행");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
System.out.println("스레드 3 완료");
});
t1.start();
t2.start();
t3.start();
}
}
✔ CountDownLatch를 사용하면 특정 스레드가 끝날 때까지 다른 스레드의 실행을 대기할 수 있음
✔ 순서대로 t1 → t2 → t3가 실행됨
🛠 출력 결과
스레드 1 실행
스레드 1 완료
스레드 2 실행
스레드 2 완료
스레드 3 실행
스레드 3 완료
🏆 4. 결론: 순차 실행을 위한 방법 비교
방법 | 특징 | 사용 사례 |
join() | join()을 사용하여 순차 실행 | 간단한 순차 실행 |
SingleThreadExecutor | ExecutorService가 자동으로 순차 실행 | 멀티 스레드 환경에서 안정적인 처리 |
CountDownLatch | 특정 조건을 만족할 때 다음 스레드 실행 | 복잡한 동기화 작업 |
🚀 5. 어떤 방법을 선택해야 할까?
- 간단한 순차 실행이 필요하면 → join()
- 관리하기 쉬운 순차 실행이 필요하면 → ExecutorService
- 여러 개의 스레드가 특정 순서로 실행되어야 한다면 → CountDownLatch
💡 즉, ExecutorService를 사용하면 가장 간단하게 순차 실행이 가능합니다! 🚀
반응형
'서버&백엔드 > 🔥 JAVA' 카테고리의 다른 글
Java | 대표적인 다형성 메드 (1) | 2025.02.04 |
---|---|
힙 메모리 부족 문제 (0) | 2025.02.04 |
스레드에서 생성된 메모리 영역은 다른 스레드에서 접근 가능할까? (0) | 2025.02.04 |
JAVA | 뮤텍스(Mutex) vs 세마포어(Semaphore) (0) | 2025.02.03 |
Java | 힙(Heap)과 스택(Stack) 메모리 (0) | 2025.02.03 |