Java Thread 클래스

Thread 클래스

Thread 클래스를 이용하는 방식은 java.lang.Thread 클래스를 상속받아서 run 메소드를 재정의(Overriding)한다. run 메소드는 스레드가 실행 동작하는 메소드로서 개발자는 이 메소드에 실행 동작할 코드를 기술하면 된다.

예제 1) Thread 1개 실행 다음은 Thread를 상속 받아서 클래스를 구현 생성하는 예제이다.

package com.devkuma.tutorial.thread; public class MyThread extends Thread { public void run() { for (int i = 0; i < 10; i++) { System.out.println("This is thread. i=" + i); } } public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); } }

실행 결과:

This is thread. i=0 This is thread. i=1 This is thread. i=2 This is thread. i=3 This is thread. i=4 This is thread. i=5 This is thread. i=6 This is thread. i=7 This is thread. i=8 This is thread. i=9

단순히 1개의 스레드 실행되기 때문에 일반 반복문과 동일한 결과를 볼 수 있다.

예제 2) Thread 2개 실행

다음은 두개의 스레드를 갖는 경우를 살펴보겠다.

package com.devkuma.tutorial.thread; public class MyThread2 extends Thread { public MyThread2(String name) { super(name); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(super.getName() + " thread. i=" + i); } } public static void main(String[] args) { MyThread2 thread1 = new MyThread2("first"); MyThread2 thread2 = new MyThread2("second"); thread1.start(); thread2.start(); } }

실행 결과:

first thread. i=0 first thread. i=1 second thread. i=0 second thread. i=1 second thread. i=2 first thread. i=2 second thread. i=3 second thread. i=4 second thread. i=5 second thread. i=6 second thread. i=7 second thread. i=8 second thread. i=9 first thread. i=3 first thread. i=4 first thread. i=5 first thread. i=6 first thread. i=7 first thread. i=8 first thread. i=9

예제1)과 비교하면 첫번째 스레드(first thread)와 두번째 스레드(second thread)가 불규칙하게 실행 되면서 각자의 결과를 표시하는 것을 볼 수 있다.




최종 수정 : 2021-08-27