프로그래밍 공부

자바 스레드(Thread) 본문

Programming/JAVA

자바 스레드(Thread)

khj1999 2024. 10. 22. 19:27

자바에서 스레드(Thread)는 하나의 프로그램 내에서 동시에 여러 작업을 실행하기 위해 사용하는
경량 프로세스이다.

자바는 멀티스레딩을 지원하여, 여러 스레드를 병렬로 실행하고, 여러 작업을 동시에 처리할 수 있다.
스레드를 사용하면 CPU를 효율적으로 사용하고, 대규모 프로그램의 성능을 개선할 수 있다.

자바에서 스레드를 사용하는 방법

자바에서 스레드를 구현하는 두 가지 주요 방법이 있다:

  1. Thread 클래스를 상속받기
  2. Runnable 인터페이스를 구현하기

1. Thread 클래스를 상속받는 방법

Thread 클래스를 상속받아 스레드를 정의하고, run() 메서드 안에 실행할 작업을 작성한다.
스레드를 시작할 때는 start() 메서드를 호출하여 스레드를 시작할 수 있다. run() 메서드는 스레드가
시작되면 실행되는 메서드이다.

class MyThread extends Thread {
    public void run() {
        // 스레드에서 실행할 작업
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
            try {
                Thread.sleep(1000);  // 1초간 대기
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();  // 스레드 실행
    }
}

2. Runnable 인터페이스를 구현하는 방법

Runnable 인터페이스를 구현하면, 다른 클래스를 상속받으면서도 스레드를 사용할 수 있다. Thread 객체에 Runnable 구현 객체를 전달하여 스레드를 실행한다.

class MyRunnable implements Runnable {
    public void run() {
        // 스레드에서 실행할 작업
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
            try {
                Thread.sleep(1000);  // 1초간 대기
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread t1 = new Thread(runnable);
        t1.start();  // 스레드 실행
    }
}

주요 스레드 메서드

  • start(): 스레드를 시작하고, run() 메서드를 호출하여 스레드 작업을 수행.
  • run(): 스레드가 실행될 때 수행될 작업을 정의. start()가 호출되면 run()이 자동으로 실행됨.
  • sleep(long millis): 스레드를 일정 시간 동안 멈춤. millis는 대기 시간(밀리초).
  • join(): 한 스레드가 종료될 때까지 다른 스레드가 기다리도록 함.
  • interrupt(): 실행 중인 스레드를 중단시킴.
  • isAlive(): 스레드가 아직 실행 중인지 확인.

예시: 두 스레드를 동시에 실행

class Task1 extends Thread {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Task1: " + i);
            try { Thread.sleep(500); } catch (InterruptedException e) {}
        }
    }
}

class Task2 implements Runnable {
    public void run() {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Task2: " + i);
            try { Thread.sleep(500); } catch (InterruptedException e) {}
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Task1 t1 = new Task1();  // Thread 클래스 상속
        Thread t2 = new Thread(new Task2());  // Runnable 인터페이스 구현

        t1.start();  // Task1 실행
        t2.start();  // Task2 실행
    }
}

동기화(Synchronization)

여러 스레드가 동일한 자원을 동시에 접근할 때는 데이터의 무결성을 보장하기 위해 동기화가 필요하다.

동기화를 하지 않으면 데이터 경쟁(Race Condition) 현상이 발생할 수 있다.

자바에서 동기화를 사용하려면 synchronized 키워드를 사용하여 스레드 간의 동시 접근을 제어할 수 있다.

class Counter {
    private int count = 0;

    // 동기화된 메서드
    public synchronized void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        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("Final count: " + counter.getCount());  // 2000
    }
}
Comments