英文:
I am unable to start a thread whiles implementing runnable can't seem to reproduce an error
问题
由于某种原因,当我实现Runnable接口时,似乎无法调用start()方法
```java
public class ThreadTest implements Runnable {
public void run() {
}
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
test.start();
}
}
在start()下面我看到了一个红色的波浪线,提示我需要实现start方法或将test强制转换为对象类型
我在在线编译器中无法复现这个错误
<details>
<summary>英文:</summary>
for some reason i cant seem to invoke the start() method when i am implementing Runnable
public class ThreadTest implements Runnable {
public void run() {
}
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
test.start();
}
}
I am getting the red wiggle line under start() saying that I need to either implement start or type cast test to object
I am unable to reproduce this error in online compiler either
[![enter image description here][1]][1]
I am beyond baffled as to what is causing this error
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/DDMPk.png
[2]: https://i.stack.imgur.com/c8vSD.png
</details>
# 答案1
**得分**: 2
请尝试这个:
```java
尝试这样做:
public class ThreadTest implements Runnable {
public void run() {
}
public static void main(String[] args) {
Thread test = new Thread(new ThreadTest());
test.start();
}
}
另一种方式:
public class ThreadTest extends Thread{
public void run() {
}
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
test.start();
}
}
英文:
try this:
public class ThreadTest implements Runnable {
public void run() {
}
public static void main(String[] args) {
Thread test = new Thread(new ThreadTest());
test.start();
}
}
another way:
public class ThreadTest extends Thread{
public void run() {
}
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
test.start();
}
}
答案2
得分: 0
你不应该这样调用
TestThread test=new TestThread();
test.start();
正确的方式是:
Thread thread=new Thread(new TestThread());
thread.start();
你可以继承Thread类或者实现Runnable接口,并重写run方法,这样当调用start方法时,它会执行run方法内部的代码。
英文:
You shoudn't call like
TestThread test=new TestThread();
test.start();
Correct way :
Thread thread=new Thread(new TestThread());
thread.start();
Either you can extend Thread class or implement Runnable class and override the run method so when u call start method it will execute the code inside the run method.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论