2021.09.14 Written
public class Thread implements Runnable {
//내부적으로 Runnable Interface 를 구현하고 있음
public Thread(Runnable target) {
this(null, target, "Thread-" + nextThreadNum(), 0);
// Thread 로 관리할 Runnable 객체를 넣어준다.
}
}
public interface Runnable {
public abstract void run();
//run() 메소드에 Thread 로 처리할 로직을 구현할 수 있음
}
Thread 의 start() 메소드가 호출되면 실행대기 상태에 있다가 JVM 의 스레드 스케줄러에 의해 자신의 차례가 되면 실행됨
스레드는 한 번 실행이 종료되게 되면 다시 사용할 수 없음 (Reusable 하지 않음). 다시 작업을 수행해야 하면 스레드를 새로운 스레드를 생성하여야 함
하나의 스레드에 대해 start() 메소드가 두 번 이상 호출하면 Runtime 시에 IllegalThreadStateException 이 발생
main 메소드의 작업을 수행하는 것도 스레드. main 메소드의 스레드가 작업을 마쳤다 하더라도 다른 스레드가 아직 작업을 마치지 않은 상태라면 프로그램은 종료되지 않음.
프로그램은 실행 중인 스레드가 하나도 없을 때 종료됨
문맥 교환(작업 전환)이라고도 하며, 프로세스 또는 스레드가 교체되는 것을 의미. 현재 진행 중인 작업의 상태 등의 정보를 저장하고 읽어 오는 시간이 소요됨
여러 스레드가 여러 작업을 동시에 진행하는 것을 병행(concurrent)이라고 하고, 하나의 작업을 여러 스레드가 나누어 처리하는 것을 병렬(parallel)이라고 함
JVM 의 Thread Scheduler 에 의해 어떤 스레드가 얼마동안 실행될 것인지가 결정되고, OS 의 Process Scheduler 에 의해 프로세스 실행순서와 실행시간이 결정됨
∴ 매 실행 시 결과가 달라지게 됨
public class Thread implements Runnable{
private int priority;
public static final int MIN_PRIORITY = 1;
public static final int NORM_PRIORITY = 5;
public static final int MAX_PRIORITY = 10;
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}
}
References
남궁 성, 『자바의 정석』, 도우출판(2016)