본문 바로가기

프로그래밍 언어/Java

[Java] 멀티스레드 프로그래밍 - Runnable 인터페이스

반응형

 

스레드(thread)

스레드란 프로그램의 실행 흐름을 뜻한다.

  • 싱글 스레드(single thread program) : 스레드가 하나뿐인 프로그램
  • 멀티스레드 프로그램(multithread program) : 스레드가 둘 이상인 프로그램

 

멀티스레드 프로그램의 작성 방법
  1. java.lang.Thread 클래스를 이용하는 방법
  2. 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 클래스 자체는 스레드 클래스가 아님. 

반응형