Java 스레드(Thread) Runnable 인터페이스
Runnable 인터페이스
Runnable 인터페이스를 이용한 방식은 java.lang.Runnable 인터페이스를 implements로 정의하고 run 메소드(Overriding)를 재정의한다. 먼저 살펴본 Thread 상속 방식과 동일하게 run 메소드에는 스레드가 실행할 코드를 기술하면 된다.
예제 1) Thread 1개
package com.devkuma.tutorial.thread;
public class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("This is thread. i=" + i);
}
}
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
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
결과는 Thread 클래스의 예제 1)과 동일하다. 이것도 스레드가 1개이기에 단순히 반복을 실행시킨 결과가 같다. 스레드가 여러 개 실행되면 동시에 여러 스레드가 실행되면서 각각 결과를 표시하게 될 것이다.