What I Learned
자바의 정석 13장 스레드
스레드의 상태
- new: 생성되고 아직 스타트 전의 상태
- runnable: 실행중 또는 실행가능한 상태
- blocked: 동기화 블럭에 의해 일시정지된 상태
- Waiting, timed-waiting = 종료되지 않았지만 실행가능하지 않은 일시정지 상태. (suspend(), sleep(), wait(), join(), I/O block)
- Terminated: 작업종료
- blocked/time waiting 풀리는 경우: time-out(sleep에서 시간 끝났을때), resume() (서스펜드를 재개), notify() goes with wait(), interrupt() force break sleep() before timeout
생성 -> 실행대기 -> 실행 -> 소멸
스레드의 실행제어
쓰레드의 실행을 제어할 수 있는 메서드가 제공된다
Untitled
13-22 sleep()
-
Static 메소드라서 자기 자신만 적용되고 특정스레드를 멈추게 하는 건 불가능하다. 예를 들어 메인에서 th1.sleep(2000)를 실행한다고 해도 영향을 받는 스레드는 th1이 아니라 메인 스레드.
-
트라이캐치문으로 꼭 감싸줘야함 (Interrupt()가 발생할 경우를 대비)
Try { thread.sleep(2000) } catch (InterrupedException e) {}
13-24 interrupt()
- Interrupt(): non-static, 다른 스레드를 인터럽트
- isInterrupted(): non-static, 다른 스레드가 인터럽트 상태를 반환
- interrupted() : Static, 해당 스레드가 인터럽트 상태 반환하고 false로 변경