我在实现可运行时无法启动线程,似乎无法复现错误。

huangapple go评论63阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年9月2日 11:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63698446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定