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");
}
}
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();
Test t = new Test(); t.run();
and it will execute in the current Thread.
You can use Thread instead Runnable.
Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor.
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.