자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Java] 11장 멀티 스레딩

728x90

✅ 1. 스래드 생성 방법

Java 에서 스레드를 만드는 방법으로는 두 가지  방법이 있습니다.

1️⃣ Thread 클래스 상속

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("Thread is running: " + Thread.currentThread().getName());
    }
}

public class ThreadClassExample {

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start(); // Start the first thread
    }
}
  • run() 메서드 안에 스레드가 실행할 코드 작성
  • start()를 호출해야 새로운 스레드가 생성되고 병렬로 실행 (run()을 직접 호출하면 단순한 메서드가 호출됨)\

2️⃣ Runnable 인터페이스 구현

class MyTask implements Runnable {

    @Override
    public void run() {
        System.out.println("Runnable task is running: " + Thread.currentThread().getName());
    }
}

public class MyTaskExample {

    public static void main(String[] args) {
        Thread t1 = new Thread(new MyTask());
        t1.start();
    }
}
  • Runnable 방식이 더 유연 -> 다른 클래스 상속 가능
  • Java 8 버전 이상에서는 람다 표현식으로 다 간단히 가능하다
public class RamdaExample {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            System.err.println("Ramda thread is running: " + Thread.currentThread().getName());
        });
        t1.start();
    }
}

✅ 2. 동기화 (synchronized 키워드)

멀티 스레딩 환경에서 여러 스레드가 동시에 같은 자원(변수, 객체)에 접근할 수 있습니다. 이때 데이터 불일치 문제를 막기 위해 동기화가 필요합니다.

1️⃣ 메서드 전체 동기화

class Counter {

    private int count = 0;

    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class MethodAll {

    public static void main(String[] args) {
        Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                counter.increment();
            }
            System.err.println("Thread 1 counter:" + counter.getCount());
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                counter.increment();
            }
            System.err.println("Thread 2 counter: " + counter.getCount());
        });

        t1.start(); // Start the first thread
        t2.start(); // Start the second Thread
    }
}
  • synchronized를 메서드에 붙이면 해당 객체(this)에 락을 걸고 실행함

2️⃣ 블록 동기화

class Counter {

    private int count = 0;

    public void increment() {
        synchronized (this) { // 특정 객체 락
            count++;
        }
    }
}

3️⃣ 정적 메서드 동기화

class Counter {

    private static int count = 0;

    public static synchronized void increment() {
        count++; // Static synchronized method to ensure the count is increment at the class level
    }

}
  • static synchronized는 클래스 자체(Class 객체)에 락을 검

4️⃣ 정리

방식 장점 단점
Thread 상속 구현 간단 다른 클래스 상속 X
Runnable 구현 유연성 높음, 람다 사용 가능 약간의 코드 추가 필요
synchronized 메서드 구현 간단, 안정성 높음 성능 저하 기능
synchronized 블록 필요한 부붐만 동기화 -> 성능 개선 구현 복잡

💡Tip (2025 최신 Java 기준)

  • Java 19~21 버전 부터 Virtual Threads(Project Loom)도 가능 -> 가볍게 수천 개의 스레드 생성 
  • Executors.newVirtualThreadPerTaskExecutor()을 사용하면 간단 병렬 처리 가능

 

 

GitHub - Koras02/java-bloging: https://thinky.tistory.com/category/Back-End/Java

https://thinky.tistory.com/category/Back-End/Java. Contribute to Koras02/java-bloging development by creating an account on GitHub.

github.com

 

728x90
LIST

'Back-End > Java' 카테고리의 다른 글

[Java] 12장 프로젝트 생성(완)  (0) 2025.08.12
[Java] 10장 파일 입출력  (0) 2025.08.06
[Java] 9장 컬렉션 프레임워크  (0) 2025.03.25
[Java] 8장 try-catch 문  (0) 2025.03.18
[Java] 7장 인터페이스  (0) 2025.03.08