Java是否可以直接调用Run()方法来启动一个新线程

时间:2020-02-23 14:33:58  来源:igfitidea点击:

不行,我们无法直接调用运行方法启动一个线程。
我们需要调用Start方法来创建一个新线程。

如果直接调用运行方法,它将不会创建一个新线程,它将与主要的堆栈相同。

package org.arpit.theitroad;
class CustomThread extends Thread {
 
 public void run() {
  for (int i = 0; i < 5; i++) {
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
   System.out.println("Thread is running :"+i);
  }
  
 }
 
}
 
public class StartThreadAgainMain {
 
 public static void main(String[] args) {
  CustomThread ct1 = new CustomThread();
  CustomThread ct2 = new CustomThread();
  ct1.run();
  ct2.run();
 
 }
 
}

运行上面的程序时,我们将得到以下输出:

Thread is running :0
Thread is running :1
Thread is running :2
Thread is running :3
Thread is running :4
Thread is running :0
Thread is running :1
Thread is running :2
Thread is running :3
Thread is running :4

正如我们在直接调用RUN方法的情况下,它不是创建新线程。

如果我们在上面的示例中使用start而不是运行:

package org.arpit.theitroad;
class CustomThread extends Thread {
 
 public void run() {
  for (int i = 0; i < 5; i++) {
   try {
    Thread.sleep(300);
   } catch (InterruptedException e) {
   
    e.printStackTrace();
   }
   System.out.println("Thread is running :"+i);
  }
  
 }
 
}
 
public class StartThreadAgainMain {
 
 public static void main(String[] args) {
  CustomThread ct1 = new CustomThread();
  CustomThread ct2 = new CustomThread();
  ct1.start();
  ct2.start();
 
 }
 
}

运行上面的程序时,我们将得到以下输出:

Thread is running :0
Thread is running :0
Thread is running :1
Thread is running :1
Thread is running :2
Thread is running :2
Thread is running :3
Thread is running :3
Thread is running :4
Thread is running :4

不能直接调用run方法来创建线程,需要调用start方法来创建新线程。