Java/쓰레드
Runnable 인터페이스
asd135
2023. 9. 28. 20:52
728x90
Runnable 인터페이스
자바에서 쓰레드를 생성하고 사용하는 또 다른 방법이다. Runnable 인터페이스를 구현하는 클래스는 run() 메서드를 오버라이드, 이 run() 메서드에는 쓰레드가 수행할 작업을 정의한다.
Runnable사용 쓰레드 생성
public class HelloWorld {
public static void main(String[] args) throws Exception{
Thread t1 = new Thread(new MyRunnable()); // 쓰레드 생성
t1.start(); // 쓰레드 시작
}
}
class MyRunnable implements Runnable {
public void run() { // run 메서드 오버라이드
for(int i=0; i<10; i++) {
System.out.println(i);
}
}
}
인터페이스를 사용하는 이유
자바가 단일 상속만 지원하기 때문이다. 만약 다른 클래스를 상속받아야 하는 경우에는 쓰레드 클래스를 상속받을 수 없기 때문에 인터페이스를 사용한다.