쓰레드 생성 방법은 크게 두가지가 있다.
1. Thread 클래스 상속받아 오버라이딩 메서드 구현
2. Runnable() 인터페이스를 구현
아래는 1번 방법으로 쓰레드를 생성한 모습이다.
run() 메서드를 새롭게 작성해주면 된다.
package first_project;
public class MyThread1 extends Thread{
String str;
public MyThread1(String str) {
this.str = str;
}
@Override
public void run() {
for(int i = 0;i<10;i++) {
System.out.println(str);
try {
Thread.sleep((int) Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package first_project;
public class MyThreadTest {
public static void main(String[] args) {
MyThread1 tr1 = new MyThread1("*");
MyThread1 tr2 = new MyThread1("-");
tr1.start();
tr2.start();
System.out.println("main finished.");
}
}
위의 코드는 메인에서 쓰레드를 생성하고 실행하는 코드이다.
주의할 점은 run() 메서드를 구현했지만 run()을 실행하면 안된다. start()를 실행해주어야 한다.
start()는 쓰레드를 생성할 준비를 하고 준비가 완료되면 run()을 실행해준다.
출력 결과
main finished.
*
-
-
*
*
-
*
-
*
-
*
-
*
-
*
-
*
-
*
-
그리고 2번 방법인 Runnable 인터페이스 구현으로 쓰레드 생성하기
package first_project;
public class MyThread2 implements Runnable{
String str;
public MyThread2(String str) {
this.str = str;
}
public void run() {
for(int i = 0;i<10;i++) {
System.out.println(str);
try {
Thread.sleep((int) Math.random()*1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package first_project;
public class MyThreadTest2 {
public static void main(String[] args) {
MyThread2 tr1 = new MyThread2("*");
MyThread2 tr2 = new MyThread2("-");
Thread thread1 = new Thread(tr1);
Thread thread2 = new Thread(tr2);
thread1.start();
thread2.start();
System.out.println("main2 finished.");
}
}
이 방법으로 쓰레드를 실행시킬 때 주의할 점은
MyThread2 자체는 쓰레드를 상속받고 있지 않기 때문에 start()를 실행할 수 없다.
그래서 Thread 객채를 하나 만들어서 인자로 Runnable 객체를 넘겨주어야 한다. 그 이후 start()를 실행하면 된다.
출력 결과
*
main2 finished.
*
-
*
-
*
-
*
-
*
-
*
-
-
*
*** 근데, 굳이 Runnable 인터페이스를 제공하는 이유가 뭘까?
- 한 클래스가 상속을 여러 개 받을 수 없기 때문이다. 어떤 클래스가 다른 클래스를 상속받고 있다면 그 클래스는 쓰레드 클래스를 상속받을 수 없다. 이 경우에도 쓰레드를 사용할 수 있게 하기 위해 Runnable 인터페이스를 제공해준다.
댓글