Java - Multithreading

개미는뚠뚠·2024년 9월 29일
0

java

목록 보기
14/15
post-thumbnail

🍞멀티스레딩(Multithreading)이란?

멀티스레딩은 하나의 프로세스 내에서 여러 스레드를 동시에 실행하여 프로그램의 성능을 향상시키는 기법을 말한다. 이를 통해 CPU 자원을 효율적으로 사용할 수 있으며, 특히 I/O 작업이나 대기 시간이 긴 작업을 처리할 때 유용하다.

멀티스레딩은 Java 프로그램의 성능을 크게 향상시킬 수 있는 강력한 도구이다.

🍞Java에서 스레드 생성하기

Java에서 스레드를 생성하는 방법에는 두 가지가 있다
Thread 클래스를 상속받는 방법과 Runnable 인터페이스를 구현하는 방법이다.

🍞🍞방법1. Thread 클래스 상속하기

class TestThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " - " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        TestThread thread1 = new TestThread();
        TestThread thread2 = new TestThread();
        thread1.start();
        thread2.start();
    }
}

🍞🍞방법2. Runnable 인터페이스 구현하기

class TestRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " - " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread1 = new Thread(new TestRunnable());
        Thread thread2 = new Thread(new TestRunnable());
        thread1.start();
        thread2.start();
    }
}

🍞🍞 스레드 동기화

멀티스레딩 환경에서 공유 자원에 대한 접근을 제어하기 위해 동기화가 필요하다. 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) {
        Counter counter = new Counter();
      
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        };

        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);
        thread1.start();
        thread2.start();

        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final Count: " + counter.getCount());
    }
}

0개의 댓글