자바(JAVA) - Thread사용하기(Join 사용)
/*
* Thread자신이 하던 작업을 잠시 멈추고 다른 쓰레드가 지정된 시간동안 작업을 수행하도록 할 떄 join()을 사용한다.
* 시간을 지정하지 않으면, 해당 쓰레드가 작업을 모두 마칠 때까지 기다리게된다.
* 작업중에 다른 쓰레드의 작업이 먼저 수행되어야할 필요가 있을때 join()을 사용한다.
*/
package Day3;
class MyRunnableTwo implements Runnable{
public void run(){
System.out.println("run"); //run 출력
first(); //first를 부른다
}
public void first(){
System.out.println("first"); //first 출력
second(); //second를 부른다
}
public void second(){
System.out.println("second"); //second 출력
}
}
public class JoinEx {
public static void main(String[] args){
System.out.println(Thread.currentThread().getName() + "start"); //현제 쓰레드의 이름(main)을 과 start를 출력한다
Runnable r = new MyRunnableTwo(); //객체생성, Runnable이 추상클래스이므로 MyRunnableTwo 초기화
Thread myThread = new Thread(r); //Thread <-객체, myThread에 thread Runnable을 넣은 객체 생성
myThread.start(); //Thread 시작
try{ //try ~ catch 예외처리
myThread.join(); //main과 thread가 같이 시작하면 누가 먼저 끝날지 모르기때문에
}catch(InterruptedException ie){ //thread 먼저 끝내고 메인을 시작할 수 있게 join을 쓴다
ie.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "end");
//앞에 join을 만낫으니 쓰레드를 돌고 현재쓰레드(main)의 이름을 가져오고 + end출력한다.
}
}