1. join()
- 지정된 시간동안 특정 쓰레드가 작업하는 것을 기다린다.
void join() // 작업이 모두 끝날 때까지
void join(long millis) // 천분의 일초 동안
void join(long millis, int nanos) // 천분의 일초 + 나노초 동안
- 예외처리를 해야 한다.(InterruptedException이 발생하면 작업 재개)
public class Ex_08 {
static long startTime = 0;
public static void main(String[] args) {
ThreadEx19_1 th1 = new ThreadEx19_1();
ThreadEx19_2 th2 = new ThreadEx19_2();
th1.start();
th2.start();
startTime = System.currentTimeMillis();
try {
th1.join(); // main쓰레드가 th1의 작업이 끝날 때까지 기다린다.
th2.join(); // main쓰레드가 th2의 작업이 끝날 때까지 기다린다.
Thread.sleep(3000);
} catch(InterruptedException e) {}
System.out.print("소요시간:" + (System.currentTimeMillis() - Ex_08.startTime));
}
}
class ThreadEx19_1 extends Thread{
public void run() {
while (!isInterrupted()) {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch(InterruptedException e){}
System.out.println("|");
}
this.interrupt();
}
}
}
class ThreadEx19_2 extends Thread{
public void run() {
while (!isInterrupted()) {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch(InterruptedException e){}
System.out.println("-");
}
this.interrupt();
}
}
}
2. yield() - static메서드
- 남은 시간을 다음 쓰레드에게 양보하고, 자신(현재 쓰레드)은 실행대기한다.
public void run() {
while(!stopped) {
if(!suspended) {
/*
작업 수행
*/
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
} else {
Thread.yield(); // 양보 -> OS스케쥴러에 통보
}
}
}
public void suspend() {
suspended = true;
th.interrupt(); // sleep상태를 깨움
}
public void stop() {
stopped = true;
th.interrupt(); // sleep상태를 깨움
}
'Java' 카테고리의 다른 글
135. wait()과 notify() - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
---|---|
134. 쓰레드의 동기화 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
132. suspend(), resume(), stop() - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
131. sleep(), interrupt() - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
130. 데몬 쓰레드, 쓰레드의 상태 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.06 |