Java 멀티스레딩 마스터하기: 스레드 제어, 동기화 및 동시성 유틸리티

발행: (2025년 12월 2일 오후 06:00 GMT+9)
3 min read
원문: Dev.to

Source: Dev.to

스레드 제어

Java는 스레드 실행을 제어하기 위한 내장 메서드를 제공합니다.

핵심 메서드

  • sleep() – 지정된 시간만큼 현재 스레드를 일시 정지합니다.
  • join() – 다른 스레드가 끝날 때까지 기다립니다.
  • yield() – 현재 스레드가 일시 정지하고 다른 스레드가 실행될 수 있도록 제안합니다.

예제

package ayshriv;

public class MasteringBackend {
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(() -> {
            for (int i = 1; i  {
            for (int i = 0; i  {
            for (int i = 0; i  {
            for (int i = 0; i  {
            for (int i = 0; i  {
            try {
                for (int i = 1; i  {
            try {
                for (int i = 1; i  {
    while (true) {
        try {
            System.out.println("Daemon thread working...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            break;
        }
    }
});
daemon.setDaemon(true);
daemon.start();

메인(사용자) 스레드가 종료되면 JVM은 데몬 스레드를 자동으로 종료합니다.

동시성 유틸리티

Java의 java.util.concurrent 패키지는 멀티스레드 프로그래밍을 단순화하는 고수준 구조를 제공합니다.

ExecutorService

import java.util.concurrent.*;

public class MasteringBackend {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Callable task = () -> {
            Thread.sleep(500);
            return 42;
        };

        Future future = executor.submit(task);
        System.out.println("Result: " + future.get());

        executor.shutdown();
    }
}

CountDownLatch

import java.util.concurrent.*;

public class MasteringBackend {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);

        Runnable worker = () -> {
            System.out.println(Thread.currentThread().getName() + " working");
            latch.countDown();
        };

        for (int i = 0; i  queue = new ArrayBlockingQueue<>(5);

        Thread producer = new Thread(() -> {
            try {
                queue.put("Message");
                System.out.println("Produced message");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                String msg = queue.take();
                System.out.println("Consumed: " + msg);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();

        producer.join();
        consumer.join();
    }
}

이러한 유틸리티는 스레드 풀링, 동기화 및 스레드 간 데이터 교환을 처리하여 저수준 synchronized 블록과 수동 스레드 관리의 필요성을 줄여줍니다.

Back to Blog

관련 글

더 보기 »

core.async: 심층 탐구 — 온라인 밋업

이벤트 개요: 12월 10일 GMT+1 기준 18:00에 Health Samurai가 온라인 밋업 “core.async: Deep Dive”를 주최합니다. 이번 강연은 clojure.core의 내부를 파헤칩니다....

모뎀의 복수

첫 번째 연결 1994년 겨울, 홍콩의 작은 아파트에서, 14세 소년이 US Robotics Sportster 14,400 Fax Modem을 연결했다.