2012-09-18 48 views
4

整個代碼:沒有可以訪問類型的封閉實例。

public class ThreadLocalTest { 
    ThreadLocal<Integer> globalint = new ThreadLocal<Integer>(){ 
     @Override 
     protected Integer initialValue() { 
      return new Integer(0); 
     } 
    }; 


    public class MyThread implements Runnable{ 
     Integer myi; 
     ThreadLocalTest mytest; 

     public MyThread(Integer i, ThreadLocalTest test) { 
      myi = i; 
      mytest = test; 
     } 

     @Override 
     public void run() { 
      System.out.println("I am thread:" + myi); 
      Integer myint = mytest.globalint.get(); 
      System.out.println(myint); 
      mytest.globalint.set(myi); 
     } 
    } 


    public static void main(String[] args){ 
     ThreadLocalTest test = new ThreadLocalTest(); 
     new Thread(new MyThread(new Integer(1), test)).start(); 
    } 
} 

爲什麼下面的代碼片段:

ThreadLocalTest test=new ThreadLocalTest(); 
    new Thread(new MyThread(new Integer(1),test)).start(); 

會導致以下錯誤:

No enclosing instance of type ThreadLocalTest is accessible. Must qualify the allocation with an enclosing instance of type ThreadLocalTest (e.g. x.new A() where x is an instance of ThreadLocalTest).


的核心問題是: 我想在靜態方法中初始化內部類。 這裏有兩種解決方案:

  1. 使內部類作爲外部類

  2. 使用外部基準,如:

new Thread(test.new MyRunnable(test)).start();//Use test object to create new

+1

什麼錯誤?我看起來像你剛剛重新粘貼代碼作爲錯誤 – Bohemian

回答

3

由於MyThread是你有一個內部類使用MyThreadTest的實例訪問它:

public static void main(String args[]) { 
    MyThreadTest test = new MyThreadTest(); 
    new Thread(test.new MyThread(new Integer(1),test)).start(); 
} 
17

如果更改類MyThread靜態,你消除這個問題:

public static final class MyThread implements Runnable 

由於您的main()方法是靜態的,你不能依靠非靜態類型或領域在沒有首先創建封閉類的實例的情況下封閉類。更好的是,甚至不需要這樣的訪問,這是通過使所討論的類是靜態的來實現的。

相關問題