본문 바로가기

하../java

ch13 join() yield()

join()

지정된 시간동안 특정 스레드가 작업하는 것을 기다린다.

void join() 작업이 모두 끝날 때까지
void join(long millis) 천분의 일초 동안
void join(long millis,int nanos) 천분의 일초 + 나노초 동안
예외처리를 반드시 해야한다
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());
}
static long startTime = 0;

	public static void main(String args[]) {
		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));
	} // main
}

class ThreadEx11_1 extends Thread {
	public void run() {
		for(int i=0; i < 30; i++) {
			System.out.print(new String("-"));
		}
	} // run()
}

class ThreadEx11_2 extends Thread {
	public void run() {
		for(int i=0; i < 30; i++) {
			System.out.print(new String("|"));
		}
	} // run()
}
출력값
-----------------------------||||||||||-||||||||||||||||||||소요시간:2

yield() (static메소드임)

- 남은 시간을 다음 스레드에게 양보하고 자신(현재 스레드)은 실행대기한다.

- yield()와 interrupt()를 적절히 사용하면 응답성과 효율을 높일 수 있다.

 

class MyThread implements Runnable {
	volatile boolean suspended = false; // volatile는 쉽게 바뀌는 변수 
	volatile boolean stopped = false;
	
	Thread th;
	
	MyThread(String name){
		th = new Thread(this, name); //Thread(Runnable r, String name)
	}
	void start() {
		th.start();
	}
	void stop() {
		stopped = true;
        th.interrupt();
	}
	void suspend() {
		suspended = true;
        th.interrupt();
	}
	void resume() {
		suspended = false;
	}
	public void run() {
		while(!stopped) {
			if(!suspended) {
				System.out.println(Thread.currentThread().getName());
				try {
					Thread.sleep(1000);
				} catch(InterruptedException e) {}
			}else{
             Thread.yield(); 위의 작업이 없을때 양보
             //yield는 os스케줄러에게 알려주는거기 때문에 반드시 동작한다는 보장이 없음
            }
			
		}
	} // run()
}