簡體   English   中英

無法創建實現Runnable接口的類的對象

[英]Unable to create an object of class which implements Runnable interface

我試圖創建一個在main方法中實現Runnable接口的類的對象,並將這些對象傳遞給線程池。 但是IDE顯示了讀取非靜態變量的錯誤,該錯誤不能從靜態上下文中引用,即,我不能首先創建對象。 我無法弄清楚這段代碼到底有什么問題。 其他所有東西都可以正常工作,但是僅這行代碼顯示了編譯錯誤。 有人可以幫忙嗎?

package threads;

import java.util.concurrent.*;

public class Tut5 {

    public static void main(String[] args) {

        ExecutorService exe = Executors.newFixedThreadPool(2);

        for(int i=0; i<5; i++) {
            Runner5 r5 = new Runner5(i);
            exe.submit(r5);
        }

        exe.shutdown();

        System.out.println("All tasks submitted.");

        try {
            exe.awaitTermination(1, TimeUnit.DAYS);
        }
        catch(InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("All tasks completed.");
    }

    class Runner5 implements Runnable {

        private int id;

        public Runner5(int id) {
            this.id = id;
        }

        public void run() {

            System.out.println("Starting thread: " + id);

            try{
                Thread.sleep(3000);
            }
            catch(InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println("Ending thread: " + id);
        }
    }
}

你去@jtahlborn

  • 非靜態變量,不能從靜態上下文中引用它-

當您在靜態方法或塊中使用非靜態實例或方法時,會出現此錯誤。

main方法是static public static void main(String[] args)因此它的簡單性將導致錯誤。

在這里,您的class Runner5 implements Runnable類是您要在靜態main方法中訪問的內部類,因此它會生成-

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

您可以在Tut5類之外定義此內部類,或將此Runner5標記為靜態。 或創建Tut5類的實例並創建方法並放置其余代碼。

謝謝

正如其他人回答,該Runner5類是內部類Tut5 這樣,它需要實例化一個外部實例

如果您使Runner5成為靜態類,它將成為不需要外部實例的靜態嵌套類

static class Runner5 implements Runnable {
...
}

但是,正如其他人指出的那樣,除非您正在對嵌套類進行練習,否則您應該將該類放在其自己的類文件中,或者您確定該類僅與Tut5類結合使用才有用,並且僅會被引用從那個班級。

請參閱http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html了解更多信息。

這里的問題是您無意中創建了一個內部類。 看來您是Java的初學者,而內部類是Java的相當高級的功能,所以我認為暫時最好避免使用它們。

在對Java更加自信之前,我建議您將每個類放入一個單獨的文件中。 Runner5類的代碼移動到單獨的文件中,將該類public並將其命名為Runner5.java 然后,您應該發現代碼可以正常編譯。

就目前而言,您的代碼定義了一個Runner5類, Runner5屬於您創建的Tut5每個實例。 但是您永遠不會創建Tut5任何實例,因此不能創建任何屬於它們的Runner5 如果將static修飾符添加到Runner5類,則內部類Runner5將屬於Tut5類,而不是此類的實例。 然后,您將可以從您的main方法中創建Runner5 但是,當您仍在學習Java時,建議您保持簡單並暫時遵循“每文件一類”的規則。

最簡單的解決方案是,只需將Runner5類復制到其自己的文件中。

除非您有很好的理由,否則我不明白為什么在這種情況下必須使用嵌套類,它不會改變任何內容(在顯示的代碼中)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM