[ch13] 쓰레드 thread


[1] 프로세스와 쓰레드


[2] 쓰레드의 구현과 실행


⇒ 구현코드

class ThreadEx1 {
	public static void main(String[] args) {
		ThreadEx1_1 t1 = new ThreadEx1_1();
		
		Runnable r = new ThreadEx1_2();
		Thread t2 = new Thread(r);			// 생성자 Thread(Runnable target)
		
		t1.start();
		t2.start();
	}
}

class ThreadEx1_1 extends Thread { // 방법 1
	public void run() {
		for (int i=0; i<5; i++) {
			System.out.println(getName());	// 조상인 Thread의 getName()을 호출
		}
	}
}

class ThreadEx1_2 implements Runnable { // 방법 2
	public void run() {
		for (int i=0; i<5; i++) {
//			Thread.currentThread();			// 현재 실행 중인 Thread를 반환
			System.out.println(Thread.currentThread().getName()); // Thread 클래스의 static 메서드인 curent Thread()를 호출하여 쓰레드에 대한 참조를 얻어와야만 호출 O
		}
	}
}

3. start()와 run()