![](/img/trans.png)
[英]The method start() is undefined for the type ServerWorker… (java Runnable)
[英]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.