2016-02-26 33 views
-1
上線

Java程序,這似乎是正常的,但有一些錯誤的UserThread ut1 = new UserThread(5, "Thread A");Eclipse的Java線程

計劃:

public class Ch10_2_2 { 

    class UserThread extends Thread { 
     private int length; 
     public UserThread(int length, String name){ 
      super(name); 
      this.length = length; 
     } 

     public void run() { 
      int temp = 0; 
      for (int i = 1; i <= length; i++) temp += i; 
      System.out.println(Thread.currentThread() + "Sum = " + temp); 
     } 
    } 

    public static void main(String[] args) { 
     System.out.println("Thread: " + Thread.currentThread()); 

     UserThread ut1 = new UserThread(5, "Thread A"); 
     UserThread ut2 = new UserThread(5, "Thread B"); 

     ut1.start(); ut2.start(); 
    } 
} 

錯誤消息:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: No enclosing instance of type Ch10_2_2 is accessible. Must qualify the allocation with an enclosing instance of type Ch10_2_2 (e.g. x.new A() where x is an instance of Ch10_2_2). at Ch10_2_2.main(Ch10_2_2.java:21)

+1

使它成爲一個靜態類。 '靜態類UserThread ...' – BevynQ

+0

正是:)非常感謝! – Snowman

回答

0

你應該改變你的UserThread班級爲static

當前,您試圖從靜態上下文中訪問「實例」類,該靜態上下文無效。使你的嵌套類static將允許你從一個靜態的上下文訪問它沒有錯誤。

有關更多信息,請參閱this question

+0

這是爲什麼downvoted?這是正確的解決方案。 – Casey

+0

如果「內部」類是靜態的,那麼只有「一個」的權利?由於OP以非線程安全的方式實例化其中的兩個,所以這不是他想要的解決方案。 –

+0

@Scary Wombat:這是不正確的。一個類是否被定義爲靜態的,在ClassLoader中只有它的一個定義。區別在於你如何引用該定義。如果嵌套類不是靜態的,則不能直接引用它。外部類的實例是必需的,即'NestedClass c = new OuterClass()。new NestedClass()' – BevynQ