Thread 사용법 및 코드예제
Thread를 사용하는 주요 방법과 코드 예제는 다음과 같습니다:
- Thread 클래스 상속:
class MyThread extends Thread {
public void run() {
// 스레드에서 실행할 코드
}
}
MyThread t = new MyThread();
t.start();
- Runnable 인터페이스 구현 (더 많이 사용됨):
class MyRunnable implements Runnable {
public void run() {
// 스레드에서 실행할 코드
}
}
Thread t = new Thread(new MyRunnable());
t.start();
- 람다식을 사용한 Runnable 구현:
Thread t = new Thread(() -> {
// 스레드에서 실행할 코드
});
t.start();
- 스레드 풀 사용 (ExecutorService):
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// 스레드에서 실행할 코드
});
주요 특징:
- Thread 클래스 상속보다 Runnable 인터페이스 구현이 더 선호됩니다.
- start() 메서드를 호출하여 스레드를 시작합니다.
- run() 메서드에 스레드가 실행할 코드를 작성합니다.
- 스레드 풀을 사용하면 스레드 생성/소멸의 오버헤드를 줄일 수 있습니다.
스레드 사용 시 주의할 점:
- 동기화 문제에 주의해야 합니다.
- 데드락을 방지해야 합니다.
- 스레드 간 통신을 위해 wait(), notify() 등을 사용할 수 있습니다.
스레드는 병렬 처리와 비동기 작업에 유용하지만, 복잡성을 증가시킬 수 있으므로 적절히 사용해야 합니다.
Citations: [1] https://mangkyu.tistory.com/258 [2] https://coding-factory.tistory.com/279 [3] https://ittrue.tistory.com/171 [4] https://engineerinsight.tistory.com/197 [5] https://velog.io/%40dm911/Java-Thread-개념-및-예제
thread와 Runnable의 차이점은 무엇인가요
Java에서 멀티스레딩을 구현할 때 Thread 클래스와 Runnable 인터페이스를 사용하는 두 가지 주요 방법이 있습니다. 이 두 가지 방법의 차이점과 각각의 장단점을 이해하는 것이 중요합니다.
Thread 클래스와 Runnable 인터페이스의 차이점
1. Thread 클래스 상속
- 구현 방법: Thread 클래스를 상속받아 run() 메서드를 오버라이드합니다.
- 예제:
- class MyThread extends Thread { public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread: " + i); } } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } }
- 장점:
- 간단한 구현: Thread 클래스를 상속받아 바로 사용할 수 있습니다.
- 단점:
- 다중 상속 불가: Java는 다중 상속을 지원하지 않기 때문에, Thread 클래스를 상속받으면 다른 클래스를 상속받을 수 없습니다.
- 재사용성 낮음: 스레드 로직을 다른 클래스에서 재사용하기 어렵습니다.
2. Runnable 인터페이스 구현
- 구현 방법: Runnable 인터페이스를 구현하고 run() 메서드를 오버라이드합니다. 그런 다음 Thread 객체를 생성할 때 Runnable 객체를 전달합니다.
- 예제:
- class MyRunnable implements Runnable { public void run() { for (int i = 0; i < 10; i++) { System.out.println("Runnable: " + i); } } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } }
- 장점:
- 다중 상속 가능: 다른 클래스를 상속받으면서 Runnable 인터페이스를 구현할 수 있습니다.
- 재사용성 높음: 스레드 로직을 다른 클래스에서 재사용하기 쉽습니다.
- 코드의 일관성 유지: 객체지향적인 설계가 가능합니다.
- 단점:
- 약간 더 복잡한 구현: Thread 객체를 생성할 때 Runnable 객체를 전달해야 합니다.
성능 차이
- 성능 차이 없음: Thread 클래스와 Runnable 인터페이스를 사용하는 두 방법 간의 성능 차이는 거의 없습니다. 두 방법 모두 Thread 객체를 생성하고 run() 메서드를 실행하는 방식이기 때문에, 성능 측면에서는 큰 차이가 없습니다.
사용 예제
Thread 클래스 상속
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
Runnable 인터페이스 구현
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Runnable: " + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
t1.start();
}
}
결론
- Thread 클래스 상속: 간단한 구현이 필요하고, 다른 클래스를 상속받을 필요가 없는 경우에 적합합니다.
- Runnable 인터페이스 구현: 다중 상속이 필요하거나, 스레드 로직을 재사용해야 하는 경우에 적합합니다.
이 두 가지 방법을 이해하고, 상황에 맞게 적절한 방법을 선택하는 것이 중요합니다.
Citations: [1] https://gnaseel.tistory.com/21 [2] https://dev-troh.tistory.com/47 [3] https://hyeo-noo.tistory.com/293 [4] https://velog.io/%40min-zi/Java-Runnable-인터페이스와-Thread-클래스-차 [5] https://okky.kr/questions/1159059
'개인 개발 공부 일지' 카테고리의 다른 글
| HashMap 동작원리 (0) | 2024.06.24 |
|---|---|
| Java 예외처리 (0) | 2024.06.24 |
| Java Collection (0) | 2024.06.24 |
| Thread 사용법 및 코드예제 (1) | 2024.06.13 |
| Java Collection (0) | 2024.06.13 |