[英]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?我正在使用匿名类学习 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
}
}
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.那是因为您需要启动 Threads - 但您只需要运行 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()
.您可以在创建线程时使用可运行对象预填充线程,然后运行它 - 线程中的
start()
方法将调用run()
。
You can simply go Test t = new Test(); t.run();
您可以简单地 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.您可以使用 Thread 代替 Runnable。
Provide a Runnable object.提供一个可运行的 object。 The Runnable interface defines a single method, run, meant to contain the code executed in the thread.
Runnable 接口定义了一个方法,run,意在包含线程中执行的代码。 The Runnable object is passed to the Thread constructor.
Runnable object 被传递给 Thread 构造函数。
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.