본문 바로가기

자바의 정석 정리

자바의 정석 - 13.2 쓰레드의 구현과 실행

13.2.1 쓰레드 구현방법

  1. Thread 클래스 상속
  2. class A extends Thread{ public void run(){} //오버라이딩 }
  3. Runnable 인터페이스 구현
  4. class B implements Runnable{ public void run(){} //구현 }

13.2.2 Thread 클래스 구현 및 실행

class ThreadEx1 extends Thread{
    public void run(){
        System.out.println(getName());
    }
}

public class A{
    public static void main(String[] args){
        ThreadEx1 t1 = new ThreadEx1();
        t1.start();
    }
}

13.2.3 Runnable 인터페이스 구현 및 실행

class ThreadEx2 implements Runnable{
    public void run(){
        System.out.println(Thread.currentThread().getName());
    }
}

public class B{
    public static void main(String[] args){
        Runnable r = new ThreadEx2();
        Thread t2 = new Thread(r);
        t2.start();
    }
}

13.2.4 쓰레드 이름지정

Thread(Runnable target, String name)
Thread(String name)
void setName(String name)

13.2.5 쓰레드 실행 - start()

  • 쓰레드 실행 시 start()를 호출 해야만 쓰레드가 실행됨
  • 무조건 실행되는 것이 아닌, 실행 대기 상태에서 자신의 차례가 되면 실행
  • 한번 실행이 종료 된 쓰레드는 다시 실행할 수 없음
  • 같은 쓰레드에서 start()를 두번 이상 호출하면 IllegalThreadStateException발생
ThreadEx1 t1 = new ThreadEx1();
t1.start();
t1.start(); //IllegalThreadStateException 발생

ThreadEx1 t1 = new ThreadEx1();
t1.start();
t1 = new ThreadEx1();
t1.start(); //정상 실행