Thread 정보.join()의 이해

2139 단어 JAVA 동시
먼저 코드 보기:
public static void main(String[] args) {
    	Thread son = new Thread(() -> {
    		Thread.sleep(5000);
			System.out.println("im thread son!!!");
    	});
    	son.start();
		son.join();
    	System.out.println("im thread main!!!");
}
    ;
im thread son!!!
im thread main!!!

join의 JDK 소스:
public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

주의 방법의synchronized 필드 (잠긴 자원은this 대상)
thread를 호출합니다.join()은join(long millis) 방법에 입력된 매개 변수가 0에 해당합니다.
그래서 원본 코드가 실제로 적용되는 코드 세그먼트는 다음과 같다.
 while (isAlive()) {
                wait(0);
            }
        }     

라인이 Alive 상태라면 wait(0) 방법을 순환해서 호출하기 때문에thread를 호출합니다.join () 방법의 경우,thread를 동시에 호출한 것과 같다.wait(),
따라서thread를 호출합니다.join () 방법의 루트가 막혀서 하위 루트가 실행된 후에 주 루트를 실행할 수 있습니다.
이 유효 코드를 주 라인으로 옮겨서 Join 방법을 대체합니다.
public static void main(String[] args) {
    	Thread son = new Thread(() -> {
    		Thread.sleep(5000);
			System.out.println("im thread son!!!");
    	});
    	son.start();
    	// son.join();         
    	
    	synchronized(son) {
    		while(son.isAlive()) {
    			//      。 son    ,        
    			son.wait(0);
    		}
    	}
    	
    	System.out.println("im thread main!!!");
    }
       ;
im thread son!!!
im thread main!!!

두 단락 코드의 코드는 의미가 완전히 같다. 두 번째 단락 코드는join의 원본 코드로join을 대체하지만join의 원리를 이해하기 쉽다.
thread 실행이 완료되었을 때 notify () 방법을 사용하고, Join 방법을 호출한 곳에서는 계속 실행합니다.

좋은 웹페이지 즐겨찾기