2013-03-02 3 views
-3

클래스에서 OuterClass에는 Thread InnerThread가 있습니다. 스레드에서 나는 OuterClass에서 메서드에 액세스해야합니다. 어떻게해야합니까? 나는 시도했다 :내부 클래스에서 외부 클래스 액세스 Java

public class OuterClass{ 

    public static void main(String[]args){ 
     Runnable thread = new innerThread(param); 
     new Thread(thread).start(); 

    public void method(param1, param2){ 
     System.out.println("Test method"); 
    } 



    public class InnerThread extends Thread{ 
     public void run(){ 
     System.out.println("Test thread") 
     OuterClass.this.method(param1, param2); 
     } 
    } 

} 

그러나 프로그램 doesnt는 방법으로 들어간다. 왜 그런데 어떻게 작동할까요?

편집 다른 작업을 수행하고 작동하므로 스레드가 실행 중임을 확인하고 (param1, param2) 메소드의 시작 부분에 인쇄 권한을 지정하므로 입력되지 않습니다. 방법. 나는 OuterClass가없는 방법 (param1, param2) 만 시도했다.

+3

"방법에 들어 가지 않습니까?" 어떻게 결정 했니? –

+1

실제로 스레드를 시작 하시겠습니까? –

+4

모호성을 제거 할 필요가 없다면'method'를 호출하는 것이 좋습니다. 이 질문은 현재 형태로는 분명하지 않습니다. [SSCCE] (http://sscce.org/)를 제공하십시오. –

답변

1

이 잘 작동 :

public class OuterClass { 

    public static void main(String[] args) throws InterruptedException { 
     Thread t = new Thread(new OuterClass().new InnerThread()); 
     t.start(); 
     t.join(); 
    } 

    public void method(String param1, String param2) { 
     System.out.println("Test method ("+param1+","+param2+")"); 
    } 

    public class InnerThread extends Thread { 

     public void run() { 
      System.out.println("Test thread"); 
      method("A", "B"); 
     } 
    } 
} 

인쇄

Test thread 
Test method (A,B) 
+0

그래, 잘 입력 된 메서드() 입력, 거기에 문제가있는 출력, 그래서 그것을 didnt 메서드를 입력하는 줄 알았는데. 내 잘못이야. – olkoza

0

이 두 개의 별도의 클래스 OuterClass
즉 OuterClass의 인스턴스를 ctreate 다른이 포함
1을 생성함으로써 달성 될 수있다, 메인 클래스.
보세요.

public class Main { 


public static void main(String arg[]){ 

OuterClass o=new OuterClass(1,3); 
    } 
    } 

class OuterClass{ 
    int param,param2; 
    InnerThread t; 

OuterClass(int x,int y){ 
this.param=x; 
this.param2=y; 
InnerThread t=new InnerThread(); 
t.start(); 
} 

public class InnerThread extends Thread{ 
     public void run(){ 
     System.out.println("Test thread"); 
     OuterClass.this.method(); 
     } 
    } 
public void method(){ 
     System.out.println(this.param+this.param2); 
    } 
} 
관련 문제