2015. 1. 14. 03:06
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

일반적으로 분리된 스레드가 종료될 때까지 대기하기 위해 while문을 사용하여 반복문 내에서 분리된 스레드의 isAlive() 메소드를 사용해 스레드의 종료 여부를 확인한다. 하지만 join()메소드를 사용해 이런 대기 작업을 대신 할 수 있다.




-----------------------



package Thread;

public class JoinDemo {
    public static void main(String[] args){
        Runnable r=new Runnable() {
           
            @Override
            public void run() {
                System.out.println("Worker thread is simulating "+"work by sleeping for 5 seconds.");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ie) {
                }
                System.out.println("Worker thread is dying");
            }
        };
        Thread thd=new Thread(r);
        thd.start();
        System.out.println("Default main thread is doing work");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ie) {
        }
        System.out.println("Default main thread has finished its work");
        System.out.println("Default main therad is waiting for worker thread "+"to die");
       
        try {
            thd.join();
        } catch (InterruptedException ie) {
        }
        System.out.println("Main thread is dying");
    }
}


기본 메인 스레드에서 작업 스레드를 시작한 후 몇가지 작업을 처리하는데 작업 스레드의 thd객체를 통해 호출된 join()메소드에 의해 작업 스레드가 종료될 때까지 대기한다.


모든 Thread 객체는 ThreadGroup 객체에 고한다. Thread 클래스는 ThreadGroup 객체를 반환하는 ThreadGroup getThreadGroup() 메소드를 선언하고 있는데 ThreadGroup 객체는 거의 사용되지 않기 때문에 무시해도 된다. 만일 논리적인 Thread 객체 그룹이 필요하다면 배열 또는 콜렉션을 사용하여 그룹핑하는 것이 더 효율적이다.



***

ThreadGroup 클래스의 몇몇 메소드는 결함이 있다. 예를 들어 int enumerate(Thread[] threads) 메소드는 인자 threads의 배열이 Thread 객체들을 저장하기에 충분한 크기가 아닐 경우 모든 액티브 스레드를 포함하지 못한다. 배열의 정확한 크기를 알기 위해 int activeCount(); 메소드에서 반환하는 값을 사용할 수 있을 거라 생각할 수도 있지만 activeCount() 메소드의 반환값은 스레드의 생성과 종료에 따라 수시로 변동이 되기 때문에 반환된 값이 정확한 배열의 크기가 될 수 없는 경우가 많다.






'Java > Working-level Java' 카테고리의 다른 글

Stream  (0) 2015.01.26
FileWriter : FIndAll  (0) 2015.01.22
Thread 2  (0) 2015.01.14
Thread  (0) 2015.01.06
System  (0) 2015.01.06
Posted by af334