我们可以在 Java 中直接调用 run() 方法而不是 start() 吗?


是的,我们可以做到。让我们看一个示例 -

示例

 实时演示

class my_thread extends Thread{
   public void run(){
      try{
         System.out.println ("The thread " + Thread.currentThread().getId() + " is currently running");
      }
      catch (Exception e){
         System.out.println ("The exception has been caught");
      }
   }
}
public class Main{
   public static void main(String[] args){
      int n = 6;
      for (int i=1; i<n; i++){
         my_thread my_object = new my_thread();
         my_object.run();
      }
   }
}

输出

The thread 1 is currently running
The thread 1 is currently running
The thread 1 is currently running
The thread 1 is currently running
The thread 1 is currently running

一个名为“my_thread”的类继承了主线程,其中定义了一个“run”函数,该函数给出正在运行的当前线程的 ID。定义了一个 try and catch 块,该块捕获异常(如果有)并显示相关的错误。在主函数中,运行一个“for”循环并创建“my_thread”类的新的对象。针对此对象调用“run”函数。

更新于:14-7-2020

341 次浏览

开启你的 职业

通过完成该课程获得认证

开始
广告
© . All rights reserved.