학습할 것(필수)
Thread 클래스와 Runnable 인터페이스
@FunctionalInterface public interface Runnable { public abstract void run(); }
//Threa의 주요 필드/ 메서드 시드니처 public class Thread implements Runnable { /* fields */ String name; // 스레드 이름 boolean daemon; // 데몬 스레드 여부 Runnable target; // 작업 객체 ThreadGroup group; //자신이 속한 ThreadGroup의 참조 static int threadInitNumber; // 익명 Thread들의 autonumbering ThreadLocal.ThreadLocalMap threadLocals; ThreadLocal.ThreadLocalMap inheritableThreadLocals; //ThreadLocal.class, InheritableThread.class 에의해 관리되는 Map 참조 final long tid; // Thread ID public static final int MIN_PRIORITY = 1; public static final int NORM_PRIORITY = 5; public static final int MAX_PRIORITY = 10; //static priorities /*public static methods*/ Thread currentThread(); void yield(); void sleep(long millis); /*constructors*/ public Thread(); ... /*instance methods*/ synchrozied void start(); void interrupt(); boolean isInterrupted; boolean isAlive(); synchronized void join(long millis) /*getter, setter methods for fieled*/ int priority; String name; ClassLoader contextClassLoader; boolean daemon; //getter ThreadGroup getThreadGroup(); //innter Enum enum State{New, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;} }
Thread클래스의 생성자중에는 Runnable 인터페이스를 하나 받아 target으로 설정하는 생성자가 있다. 이 생성자를 통해 타겟 작업을 설정한 가장 간단한 스레드 객체를 생성할 수 있다.
- Thread의 toString 메서드는 “Thread[<threadName>, <pritority>, <groupName>”을 반환한다.
Runnable 인터페이스는 run 이라는 메서드를 하나만 가진 @FunctionalInterface이다. 그러므로 재활용을 하지 않는 경우에는 람다식을 통해 생성하는 것이 좋다.
public Thread(Runnable target) { this(null, target, "Thread-" +nextThreadNum(), 0); }
Thread myThread = new Thread(() -> System.out.println("Hello Thread"));
myThread는 run 메서드와 start 메서드를 사용해 전달받은 작업객체인 Runnable target을 실행 할 수 있다.
- run - 그냥 작업 실행/ 대부분의 경우 호출 X
- start - 스레드 그룹에 대한 관리 및 호출 스택(call satck) 생성 후 실행
쓰레드의 상태
쓰레드의 상태는 innter enum인 Thread.State 이넘 값으로 표현된다.
State | 설명 |
NEW | Thread state for a thread which has not yet started |
RUNNABLE | Thread state for a runnable thread.
A thread in the runnable state is executing in the JVM,
but it may be waiting for other resources from the OS such as processor. |
BLOCKED | Thread state for a thread blocked waiting for a monitor lock.
A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.
사용하고자 하는 객체의 락이 풀릴 때까지 기다리는 상태 |
WAITING | A thread in the waiting state is waiting for another thread to perform a particular action.
e.g.) a thread that has called Object.wait( ) on an object is waiting for another thread to call Object.notify( ) or Object.notifyAll( ) on that Object.
A thread that has called Thread.join( ) is waiting for a specified thread to terminate.
다른 쓰레드가 통지할 때까지 기다리는 상태 |
TIMED_WAITING | Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:
- Thread.sleep
- Object.wait with timeout
- Thread.join with timeout
- LockSupport.parkNanos/ LockSuppot.parkUntil
주어진 시간 동안 기다리는 상태 |
TERMINATED | Thread state for a terminated thread. The thread has completed execution. |


화살표 | 이전 | 이후 | 어떻게? |
(1) | RUNNABLE | RUNNING | OS의 run 실행 |
(2) | 실행 | WAITING | Object.wait
- 동기화(synchronized) 블록 내에서 스레드를 일시 정지 상태로 만듭니다.
Thread.join
- 다른 쓰레드의 종료를 기다림 |
ㅤ | ““ | TIMED_WAITING | Thread.sleep |
ㅤ | ““ | BLOCKED | 락걸린 객체에 접근 |
(3) | WAITING | RUNNABLE | Object.notify |
ㅤ | TIMED_WAITING | ““ | Timeout이 종료됨 |
ㅤ | BLOCKED | ““ | 객체에 락이 풀림 |
ㅤ | 모든 일시정지 상태 | “”” | Object.interrupt( )호출
→ InterruptedException 발생 |


쓰레드의 우선순위
Priority - 1~10의 int 값으로 OS의 쓰레드 스케쥴링에 사용되는 Priority 값을 설정합니다.
Thread.MIN_PRIORITY //= 1; 가장 낮은 우선순위 Thread.NORM_PRIORITY //= 5; 중간 정도의 우선순위 - default Thread.MAX_PRIORITY //= 10; 가장 우선 순위가 높다. (잘 선택됨)
- OS의 쓰레드 스케쥴링에 사용되는 Priority는 OS 별로 다르며 JVM 이 Java의 Priority를 바탕으로 OS에 맞는 Priority를 설정합니다.
- Priority는 절대적이지 않습니다. OS의 상황 및 판단에 따라 Priority와 반대대는 실행 순서를 가질 수 있습니다.
Main Thread
- 자바 프로그램이 실행되면 항상 단 하나의 쓰레드 - 메인 쓰레드가 실행됩니다.
- 메인 쓰레드가 종료되더라도 생성된 쓰레드가 실행 중 이라면 모든 쓰레드가 작업을 완료하고 종료될 때 까지 프로그램은 종료되지 않습니다.
동기화 - Synchronization
수행되는 시점을 조절하여 서로가 알고 있는 정보가 일치하는것
Thread Synchronization = 쓰레드 동기화
자바에서 동기화를 지원하는 방식에는 크게
synchronized
키워드를 활용하는 방식과 java.util.concurrent.Lock
인터페이스를 활용하는 방식이 있습니다.Lock
인터페이스를 활용하면 더욱 정교한 동기화 Issue를 핸들링 할 수 있지만 코드의 복잡도가 올라간다는 단점이 있습니다. synchronized
키워드는 러프하게 말해서 Lock
의 구현체 중 ReetranceLock
에 fairness
flag를 false
로 준 경우를 편하게 사용하는 것이라고 생각할 수 있습니다.데드락 - DeadLock
데드락은 두개 (이상)의 쓰레드가 서로가 상대방이 원하는 자신의 자원을 물고 상대방의 자원을 원하며 서로 양보하지 않는 상황을 말합니다.
’자원’에는
Lock
인터페이스, syncrhonized
block의 진입 (monitor object) 혹은 파일의 접근, Database의 table 등이 있습니다.synchronized
키워드, Lock
인터페이스 및 데드락 과 동기화에 관한 자세한 내용은 아래의 링크를 참고해주세요