static void sleep(long millis)
static void sleep(long millis, int nanos)
try{
Thread. sleep (1, 500000); // 쓰레드를0.0015초동안멈추게한다.
} catch (InterruptedException e) ()
void delay(long millis) {
try {
Thread.sleep(millis);
} catch(InterruptedException e) {}
}
public static void main (String[] args) {
ThreadEx13_2 th1 = new ThreadEx13_2();
th1.start();
th1.interrupt(); //interrupt()를 호출하면,interrupted 상태가 true가된다.
...
System.out.println ("isInterrupted():"+ th1.isInterrupted()); // true
}
-> dead-lock 우려로 인해 사용을 권장하지 않음.
class ThreadEx17 implements Runnable {
boolean suspended = false;
boolean stopped = false;
public void run() {
while (!stopped)
if (!suspended) (
/*쓰레드가수행할코드를작성*/
}
}
}
public void suspend() { suspended = true; }
public void resume() { suspended = false; }
public void stop() { stopped = true; }
지정된 시간동안 특정 쓰레드가 작업하는 것을 기다린다.
void join() // 작업이 모두 끝날 때까지
void join(long millis) // 천분의 일초 동안
void join (long millis, int nanos) // 천분의 일초 + 나노초 동안
예외처리를 해야 한다.(InterruptedException이 발생하면 작업 재개)
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의 작업이 끝날 때까지 기다린다.
} catch (InterruptedException e) {}
System.out.print ("소요시간 : " + (System.currentTimeMillis ()
- ThreadEx19.startTime));
} // main
class MyThreadEx18 implements Runnable {
boolean suspended = false;
boolean stopped = false;
Thread th;
MyThreadEx18(String name) {
th = new Thread(this, name);
}
public void run () {
while (!stopped) {
if (!suspended) {
/*
작업수행
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
} else {
Thread.yield(); // OS 스케줄러에게 통보하는 것이기 때문에 크게 다르지 않을 수 있음.
}
}
}
}
public void start() { th.start(); }
public void suspend() {
suspended = true;
th.interrupt();
}
public void resume() { suspended = false; }
public void stop() {
stopped = true;
th.interrupt();
}