static void sleep(long millis) static void sleep(long millis, int nanos)
sleep()에 의해 일시정지 상태가 된 쓰레드는 지정된 시간이 다 되거나 interrupt()가 호출되면, InterruptedException이 발생되어 잠에서 깨어나 실행대기 상태가 된다. 그래서 항상 sleep()을 호출할 때는 try - catch문으로 예외처리를 해줘야 한다.
try { Thread.sleep(1, 500000); // 쓰레드를 0.0015초 동안 멈추게 한다. } catch(InterruptedException e) {}
🌱 interrupt()
진행 중인 쓰레드의 작업이 끝나기 전에 취소시켜야 할 때가 있다. 예를 들어, 큰 파일을 다운로드받을 때 시간이 너무 오래 걸리면 중간에 다운로드를 포기하고 취소할 수 있어야한다. 이때 interrupt()는 쓰레드에게 작업을 멈추라고 요청한다.
void interrupt() // 쓰레드의 interrupted 상태를 false에서 ture 로 변경 boolean isInterrupted() 쓰레드의 interrupted 상태를 반환 static boolean interrupted() 현재 쓰레드의 interrupted 상태를 반환 후, false로 변경
🌱 join()
join() - 다른 쓰레드의 작업을 기다린다.
쓰레드가 자신이 하던 작업을 잠시 멈추고 다른 쓰레드가 지정된 시간동안 작업을 수행하도록 할 때 join()을 사용한다.
시간을 지정하지 않으면 해당 쓰레드가 작업을 모두 마칠 때까지 기다리게 된다.
try-catch문을 써야한다.
sleep()과 다른점은 join()은 현재 쓰레드가 아닌 특정 쓰레드에 대해 동작하므로 static메서드가 아니라는 것이다.
try { th1.join(); // 현재 실행중인 쓰레드가 쓰레드 th1의 작업이 끝날 때까지 기다린다. } catch(InterruptedException e) {}
🌱 yield()
자신에게 주어진 실행시간을 다음 차례의 쓰레드에게 양보한다.
public class ex13_11 {
static long startTime = 0;
public static void main(String[] args) {
// join()과 yield()
ThreadEx11_1 th1 = new ThreadEx11_1();
ThreadEx11_2 th2 = new ThreadEx11_2();
th1.start();
th2.start();
startTime = System.currentTimeMillis();
try {
th1.join(); // main쓰레드가 th1의 작업이 끝날 때까지 기다린다.
th2.join(); // main쓰레드가 th2의 작업이 끝날 때까지 기다린다.
} catch(InterruptedException e) {}
System.out.print("소요시간: " + (System.currentTimeMillis() - ex13_11.startTime));
}
}
class ThreadEx11_1 extends Thread {
public void run() {
for(int i = 0; i < 300; i++) {
System.out.print(new String("-"));
}
}
}
class ThreadEx11_2 extends Thread {
public void run() {
for(int i = 0; i < 300; i++) {
System.out.print(new String("|"));
}
}
}
---
----------||||||||||||||||||||||||||---------||||||||||||||||||||||||-----
----------------------------------------|||||||||||||||---------------||---
-||||||||------------------|||||||--|||||||||||------------||||-------------
-------||||||--------|||||||||||--------|||||||----|||||-----||||||||||-----|
||||||||||||||--|||--------------------------------|||||||----------||||||||-
-----------|||||||--------------|||------------------------------------------
-----------------------||||||||||||||||||||||||||||||||||||||||||||||||||||||
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||소요시간: 4