2016-06-24 4 views
3

여기에서 읽은 것에서 Thread join on itself; 자체에서 호출하면 방법을 결합스레드가 자체적으로 join()을 호출하면 어떻게됩니까

, 내가 현재 ocajp 8 인증을 준비하는 덤프를 통과하고 난이 질문을 받았을 때, 내가 생각하는 것은 영원히

을 기다려야 주요이다하고 영원히

을 기다려야한다

 public class startinginconstructor extends Thread 
    { 
     private int x=2; 
     startinginconstructor() 
     { 
      start(); 
     } 
     public static void main(String[] args) throws Exception 
     { 
     new startinginconstructor().makeitso(); 
     } 
     public void makeitso() throws Exception 
     { 
      x=x-1; 
      System.out.println(Thread.currentThread().getName()+" about to call join "); 
      join(); 
      System.out.println(Thread.currentThread().getName()+" makeitso completed "); 

      // above line shouldn't be executed (method shouldn't be completed as well)since it joined on itself..? 

     } 
     public void run() 
     { 
    System.out.println(Thread.currentThread().getName()+" run started "); 
     x*=2; 
    System.out.println(Thread.currentThread().getName()+" run about to complete "); 
     } 
    } 

프로그램은 내가 잘못 영원히 기다리는 스레드의 의미를 받으셨어요 출력

main about to call join 
Thread-0 run started 
Thread-0 run about to complete 
main makeitso completed 

다음과 같이 종료 또는 무언가가있다 내가

메모를 놓친 거지 : 내가 생성자에서 스레드를 시작 알고 ..이 그래서 난 그냥 (* 거의 정확한 사실, 난에에 println 문을 배치하지 붙여 덤프의 정확한 질문은 권장 방법입니다하지 않습니다 프로그램의 흐름을 참조하십시오)

답변

8

예제에서 자신을 결합하는 스레드가 없습니다.

예제의 main() 스레드는 새 스레드를 만든 다음 새 스레드를 조인합니다.

는 혼동하지 마십시오 Thread (즉, 자바 객체) 스레드 (코드의 실행.) 당신의 모든 메소드가 같은 Thread 객체에 속하지만, 두 개의 서로 다른 스레드에서 실행에.

3

제임스는 정확합니다 (+1). 좀 더 명확하게하려고합니다. 다음은 발생합니다.

주 스레드는 startinginconstructor 생성자를 생성합니다.

생성자는 start를 호출하여 startin constructor 객체가 새 스레드에서 run 메소드를 갖게됩니다.

그런 다음 주 스레드는 makeitso를 호출합니다. makeitso에서 starting backconstructor 객체는 this입니다. 따라서 주 스레드는 startingin constructor 객체가 나타내는 스레드가 완료 될 때까지 대기합니다.

Java 객체는 객체가 스레드를 확장했기 때문에 모든 스레드에서 호출 할 수 있습니다. 해당 스레드에서 해당 메소드 호출이 발생하고 있다는 것을 의미하지는 않습니다.

+0

고맙습니다. 이해했습니다 ... – viru

관련 문제