Skip to content
Advertisement

The method start() is undefined for the type Runnable

I am learning java 8 with anonymous classes, i cant find start method, am i doing something wrong here?

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
    }
    
}

this works fine,

// 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"); 
    } 
}

Advertisement

Answer

That’s because you need to start Threads – but you only need to run Runnables.

A thread makes it run in parallel (kind of) to the currently executing thread. A runnable just runs in the current thread. You can pre-populate a Thread with a runnable when you create it and then run it – the start() method in the Thread will call run().

You can simply go Test t = new Test(); t.run(); and it will execute in the current Thread.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement