2016-02-29 26 views
0

我一直在嘗試運行多線程,但我得到的錯誤可以任何一個幫助我,我一直在改變這個洞很多,但我還沒有找到方法解決這個問題:「不能使用類型爲programa4的封閉實例,必須使用類型爲programa4的封閉實例限定分配(egxnew A(),其中x是programa4的一個實例)。」 謝謝大家。沒有可以訪問類型的封閉實例。錯誤和任何機構可以幫助我一直在嘗試改變一切,但沒有結果

public class programa4 { 

public static void main(String[] args) { 

    int t=Integer.parseInt(args[0]); 
    int x=1;    

    String z=args[1]; 

      while(x<=t){ 
       System.out.println("Iniciando hilo "+x); 
       new hilo(z).start(); 
       x=x+1; 
      } 
} 
class hilo extends Thread{ 
int num; 
String z; 
hilo(String z){ 
    this.num=Integer.parseInt(z); 
} 

public void run() { 
    int t=1; 
    while(t<=num){ 
    System.out.println("Generando iteracion: "+ t); 
    double x=Math.random()*10; 
    System.out.println("Esperando "+ x +" segundos"); 
    try { 
     Thread.sleep((long)x*1000); 
     System.out.println("Iteracion terminada"); 


    } catch (InterruptedException e) { 
     System.out.println("Se interrumpio."); 
    } 
    t=t+1; 
    } 
    System.out.println("Terminado hilo."); 

} 
} 
} 
+0

'static class hilo extends Thread' - add ** static **。 – OldCurmudgeon

+1

可能重複的[Java - 沒有封閉的Foo類型的實例可以訪問](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – Raedwald

回答

2

由於hiloprograma4inner class必有之前,首先你可以創建一個內部爲它的programma4的isnstance。

使它static class hilo打破了這一要求。

static class hilo extends Thread { 

另一種方法是創建一個programa4將其附加到。

new programa4().new hilo(z).start(); 
+0

謝謝,它的工作,我沒有想到這一點 –

相關問題