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

时间:2012-01-30 17:10:49

标签: java multithreading inheritance interface inner-classes

为什么我必须在内部类中扩展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();

 }

}

2 个答案:

答案 0 :(得分:6)

这是因为实现Runnable并没有为start方法提供类。您需要创建Thread才能运行Inner

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

答案 1 :(得分:1)

Runnable不提供start()方法。实际上你需要创建一个Thread来运行Inner类