자바에서 쓰레드(Thread)를 사용하는 방법은 2가지가 있다.
1. Thread를 직접상속 받아 사용하는 방법.
2. Runnable 인터페이스를 구현하는 방법.
두 가지 모두 알아보겠지만 자바에서는 다중 상속이 불가능하기 때문에 1번 방법을 사용하면 다른 클래스를 상속받을 수 없다.
따라서 왠만하면 2번 방법을 추천한다.
1. Thread를 직접상속 받아 사용하는 방법.
쓰레드
1
2
3
4
5
6 |
public class MyExtendThread extends Thread { public void run() { //구현 System.out.println( "Thread1" ); } } |
메인
1
2
3
4
5
6
7
8
9 |
public class JavaTestMain { public static void main(String[] args) { Thread t = new MyExtendThread(); t.start(); } } |
MyExtendThread의 생성자를 만들어 자료구조나 다른 인자들을 넘겨줄 수도 있다.
2. Runnable 인터페이스를 구현하는 방법.
쓰레드
1
2
3
4
5
6
7
8 |
public class MyRunnableThread implements Runnable { public void run() { //구현 System.out.println( "Thread2" ); } } |
메인
1
2
3
4
5
6
7
8
9
10
11 |
public class JavaTestMain { public static void main(String[] args) { MyRunnableThread t1 = new MyRunnableThread(); Thread t2 = new Thread(t1); // thread에 runnable을 넘겨준다. t2.start(); } } |
가끔 t1.run()을 직접 사용하는 사람이 있는데 옳지 않은 방법이다. 그렇게 하면 Thread의 join이나 interrupt등의 멤버함수를 사용할 수 없게 된다.
MyRunnableThread의 생성자를 만들어 자료구조나 다른 인자들을 넘겨줄 수도 있다.
쓰레드의 주요 함수
start 쓰레드를 시작한다.
join 쓰레드가 종료될 때 까지 기다린다.
interrupt 쓰레드에 인터럽트를 날린다. 인터럽트를 받으면 해당 스레드는 InterruptedException이 발생한다. 쓰레드에 try
catch문을 사용해서 interrupt처리한다.
Thread 참고 자료
http://docs.oracle.com/javase/tutorial/essential/concurrency/threads.html
출처 : http://arer.tistory.com/47
'공부 > JAVA' 카테고리의 다른 글
run()과 start()의 차이 - 멀티 쓰레드(Multi Thread) (0) | 2014.04.29 |
---|---|
자바 쓰레드 정리 (0) | 2014.04.28 |
Thread 예제 01 (0) | 2014.04.28 |
자바 Thread 쓰레드 개념 예제 소스 (0) | 2014.04.28 |
이클립스 text font 크기 키우기 (이클립스 글자 키우기) (0) | 2014.04.28 |