05.보조스레드
보조스레드의 종료 문제와 waiting 상태
메인 스레드가 끝나면 보조 스레드는 어떻게 되는가?
메인스레드보다 서브 스레드가 더 늦게 종료 되는 경우는?
프로세스가 아직 실행된다
서브 스레드가 종료한 후에 내가 처리할 로직이 있을 때 기다리기
- join()메소드 활용하기
package javastudy;
public class Proagram5 {
public static void main(String[] args) {
Thread th = Thread.currentThread();
th.setName("Main");
Runnable subMain = new Runnable() {
@Override
public void run() {
System.out.printf("%s: %s\n ", th.getName(), th.getState());
print();//메인스레드의 상태를 출력하기
System.out.printf("%s: %s\n ", th.getName(), th.getState());
}
};
Thread th1 = new Thread(subMain);
th1.setName("sub1");
// 스레드 이름 , 스레드 상태
System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
th1.start(); // 꼭 있어야 한다
// print();
System.out.printf("%s: %s\n ", th1.getName(), th1.getState());
if (th1.isAlive())
System.out.println("th1이 아직 작업중입니다");
try {
th1.join();// 조인을 해서 기다린다 보조스레드를 기다린다
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("=========Main Exit============");
}
private static void print() {
Thread th = Thread.currentThread();
for (int i = 0; i < 100; i++) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 메인일 경우 다르게 호출하고 싶을경우
if (th.getName().equals("Main"))
System.out.printf("<%s[%d] : %d\n", th.getName(), th.getId(), i + 1);
else
System.out.printf("%s[%d] : %d\n", th.getName(), th.getId(), i + 1);
}
}
}
sub1: NEW
sub1: NEW
sub1: NEW
sub1: NEW
sub1: RUNNABLE
th1이 아직 작업중입니다
Main: RUNNABLE
sub1[14] : 1
sub1[14] : 2
sub1[14] : 3
sub1[14] : 4
sub1[14] : 5
sub1[14] : 6
sub1[14] : 7
sub1[14] : 8
sub1[14] : 9
sub1[14] : 10
sub1[14] : 11
sub1[14] : 12
sub1[14] : 13
sub1[14] : 14
sub1[14] : 15
sub1[14] : 16
sub1[14] : 17
sub1[14] : 18
.
.
.
sub1[14] : 100
Main: WAITING //보조 스레드가 끝나고 메인 스레드가 종료된다
=========Main Exit============
댓글남기기