为什么我的“Runnable”没有“start”方法?

发布于 2024-12-31 22:33:34 字数 939 浏览 3 评论 0原文

为什么我必须在内部类中扩展 Thread 而不是实现 Runnable 以下代码有效:-

class Outer{

 Inner innerObj;

 Outer(){
  innerObj = new Inner();
 }

 public void begin(){

  innerObj.start();
 }

 class Inner extends Thread{

  Inner(){
   System.out.println("Thread initialized!");
  }

  public void run(){

    System.out.println("Thread running!");

  }  
 }
}

class Driver{

 public static void main(String[] args){

  Outer o1 = new Outer();
  o1.begin();

 }

}

但是使用 Runnable 会导致编译错误:-

class Outer{

 Inner innerObj;

 Outer(){
  innerObj = new Inner();
 }

 public void begin(){

  innerObj.start();
 }

 class Inner implements Runnable{

  Inner(){
   System.out.println("Thread initialized!");
  }

  public void run(){

    System.out.println("Thread running!");

  }  
 }
}

class Driver{

 public static void main(String[] args){

  Outer o1 = new Outer();
  o1.begin();

 }

}

Why is it that i must extend Thread in an inner class instead of implementing Runnable
The following code works:-

class Outer{

 Inner innerObj;

 Outer(){
  innerObj = new Inner();
 }

 public void begin(){

  innerObj.start();
 }

 class Inner extends Thread{

  Inner(){
   System.out.println("Thread initialized!");
  }

  public void run(){

    System.out.println("Thread running!");

  }  
 }
}

class Driver{

 public static void main(String[] args){

  Outer o1 = new Outer();
  o1.begin();

 }

}

However using a Runnable causes a compile error:-

class Outer{

 Inner innerObj;

 Outer(){
  innerObj = new Inner();
 }

 public void begin(){

  innerObj.start();
 }

 class Inner implements Runnable{

  Inner(){
   System.out.println("Thread initialized!");
  }

  public void run(){

    System.out.println("Thread running!");

  }  
 }
}

class Driver{

 public static void main(String[] args){

  Outer o1 = new Outer();
  o1.begin();

 }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

生死何惧 2025-01-07 22:33:34

这是因为实现 Runnable 不会为类提供 start 方法。您需要创建一个Thread来运行Inner

Inner i = new Inner();
Thread t = new Thread( i );

That's because implementing Runnable doesn't give a class the start method. You will need to create a Thread to run the Inner.

Inner i = new Inner();
Thread t = new Thread( i );
深爱不及久伴 2025-01-07 22:33:34

Runnable 不提供 start() 方法。您实际上需要创建一个线程来运行内部类

Runnable doesn't provide a start() method . You actually need to create a Thread to run the Inner class

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文