반응형
스레드(thread)
스레드란 프로그램의 실행 흐름을 뜻한다.
- 싱글 스레드(single thread program) : 스레드가 하나뿐인 프로그램
- 멀티스레드 프로그램(multithread program) : 스레드가 둘 이상인 프로그램
멀티스레드 프로그램의 작성 방법
- java.lang.Thread 클래스를 이용하는 방법
- java.lang.Runnable 인터페이스를 이용하는 방법
Runnable 인터페이스를 이용한 멀티스레드 프로그램
1. 스레드 클래스의 객체 생성
SmallLetters obj = new SmallLetters();
// Runnalbe 인터페이스를 구현하는 클래스의 객체를 생성해서 Thread 생성자의 파라미터로 사용
Thread thread = new Thread(obj);
2. 스레드를 시작하는 start 메소드를 호출
thread.start();
public class MultithreadExample3 {
public static void main(String args[]) {
Thread thread = new Thread(new SmallLetters()); // 스레드를 생성
thread.start(); // 스레드를 시작
char arr[] = { 'ㄱ', 'ㄴ', 'ㄷ', 'ㄹ', 'ㅁ', 'ㅂ', 'ㅅ' };
for (char ch : arr)
System.out.println(ch);
}
}
class SmallLetters implements Runnable {
public void run() { // 스레드가 해야할 일을 run 메소드 안에 쓴다.
for (char ch = 'a'; ch <= 'z'; ch++)
System.out.print(ch);
}
}
출력
ㄱㄴㄷㄹㅁㅂㅅabcdefghijklmnopqrstuvwxyz
⚠️ SamllLetters 클래스 자체는 스레드 클래스가 아님.
반응형
'프로그래밍 언어 > Java' 카테고리의 다른 글
JDBC - Unknown column in 'where clause' 에러 해결 (0) | 2019.11.27 |
---|---|
[Java] 멀티스레드 프로그래밍 - 스레드간의 커뮤니케이션 (0) | 2019.11.04 |
[Java] 멀티스레드 프로그래밍 - Thread 클래스 (0) | 2019.10.28 |
[Java] GUI 프로그래밍 (0) | 2019.09.29 |
[Java] 객체의 직렬화 serialization & 역직렬화 deserialization (0) | 2019.09.23 |