簡體   English   中英

對於 Runnable 類型,方法 start() 未定義

[英]The method start() is undefined for the type Runnable

我正在使用匿名類學習 java 8,我找不到啟動方法,我在這里做錯了嗎?

class Tester {
    
    void doWork() {
        
        Runnable r = new Runnable() {

            @Override
            public void run() {
                                
            }
            
        };
        
        r.run();
        r.start(); // showing ERR The method start() is undefined for the type Runnable
    }
    
}

這工作正常,

// Here we can extends any other class 
class Test extends Geeks implements Runnable { 
    public void run() 
    { 
        System.out.println("Run method executed by child Thread"); 
    } 
    public static void main(String[] args) 
    { 
        Test t = new Test(); 
        t.m1(); 
        Thread t1 = new Thread(t); 
        t1.start(); 
        System.out.println("Main method executed by main thread"); 
    } 
}

那是因為您需要啟動 Threads - 但您只需要運行 Runnables。

線程使其與當前正在執行的線程並行(某種)運行。 可運行的只是在當前線程中運行。 您可以在創建線程時使用可運行對象預填充線程,然后運行它 - 線程中的start()方法將調用run()

您可以簡單地 go Test t = new Test(); t.run(); Test t = new Test(); t.run(); 它將在當前線程中執行。

您可以使用 Thread 代替 Runnable。

提供一個可運行的 object。 Runnable 接口定義了一個方法,run,意在包含線程中執行的代碼。 Runnable object 被傳遞給 Thread 構造函數。

https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

暫無
暫無

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

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