线程类Java

问题描述

我有这个线程类:

class tCallTime implements Runnable {
  private Thread t;
  private String threadName;
  public tCallTime(String name) {
    threadName = name;
    println("Creating " +  threadName );
  }
  tCallTime() {
  
  }
  void codeToRun() {
    //Override This
    callTime();
  }

  public void run() {
    println("Running " +  threadName );
    try {
      codeToRun();
      Thread.sleep(0);
    } 
    catch (InterruptedException e) {
      println("Thread " +  threadName + " interrupted.");
    }
  }

  public void start () {
    if (t == null) {
      t = new Thread (this,threadName);
      t.setPriority(10);
      println("Started " + threadName +  " with priority " + t.getPriority());
      t.start ();
    }

我试图通过以下方法从中继承:

class tCalcVertex extends tCallTime{
  @Override
  void codeToRun(){
  
    print("test");
  }
}

然后我尝试使用以下代码运行它:

  tCallTime thread = new tCallTime("Thread-1");
  thread.start();
  tCalcVertex thread2 = new tCalcVertex("Tread-2");
  thread2.start();

然后,编译器告诉我“构造函数“ tCalcVertex(String)”不存在“ 我将如何从此类继承而无需重写整个类

解决方法

好吧,编译器是正确的,您的类tCalcVertex中没有没有构造函数,它使用字符串。在其父类中只有一个。构造函数不会自动继承,您必须为层次结构中的每个类显式定义它们:

class tCalcVertex extends tCallTime {
  public tCalcVertex(String name) {
    super(name);
  }

  @Override
  void codeToRun() {
    print("test");
  }
}

PS Java命名约定在PascalCase中使用大写字母作为第一个字符来命名类。遵循此约定,使其他程序员可以更轻松地快速理解您的代码。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...