본문 바로가기

프로그래밍 언어/Java

[Java] 멀티스레드 프로그래밍 - Thread 클래스

반응형

 

스레드(thread)

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

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

 

멀티스레드 프로그램의 작성 방법
  1. java.lang.Thread 클래스를 이용하는 방법
  2. java.lang.Runnable 인터페이스를 이용하는 방법

 

Thread 클래스를 이용한 멀티스레드 프로그램

java.lang.Thread 클래스와 서브클래스들을 스레드 클래스(thread class)라고 부름

 

1. 스레드 클래스의 객체 생성

Thread thread = new DigitThread();

2. 스레드 객체에 대해 start 메소드를 호출

thread.start();
public class MultithreadExample1 { // main 메소드를 포함하는 클래스 
	public static void main(String args[]) {
		Thread thread = new DigitThread();  // 스레드를 생성 
		thread.start(); // 스레드를 시작
		for (char ch = 'A'; ch <= 'Z'; ch++)
			System.out.print(ch);
	} 
}

class DigitThread extends Thread { // 숫자를 출력하는 스레드 클래스 
	public void run() { // 스레드가 해야할 일을 run 메소드 안에 쓴다.
		for (int cnt = 0; cnt < 10; cnt++) 
			System.out.print(cnt);
	}
}

 

출력

ABC01234567DEFGHIJKLMNOPQRSTUVWXY89Z

두개가 동시에 실행되므로 알파벳과 숫자가 섞여서 출력된다.

 

  • sleep 메소드 : 일정 시간이 경과되기를 기다리는 메소드
Thread.sleep(1000);
public class MultithreadExample1 {
	public static void main(String args[]) {
		Thread thread = new DigitThread(); // 스레드를 생성
		thread.start(); // 스레드를 시작
		for (char ch = 'A'; ch <= 'Z'; ch++) {
			System.out.print(ch);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}

class DigitThread extends Thread {
	public void run() { // 스레드가 해야할 일을 run 메소드 안에 쓴다.
		for (int cnt = 0; cnt < 10; cnt++) {
			System.out.print(cnt);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
	}
}

 

출력

A0B12C3D4E5F6GH7I8J9KLMNOPQRSTUVWXYZ

알파벳과 숫자가 하나씩 출력된다. 

반응형