Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 start() 대신 run() 메서드를 직접 호출할 수 있습니까?

<시간/>

네, 그렇게 할 수 있습니다. 예를 들어 보겠습니다 -

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'라는 이름의 클래스는 실행 중인 현재 스레드의 ID를 제공하는 '실행' 기능이 정의된 기본 스레드를 상속합니다. 예외(있는 경우)를 포착하고 관련 오류를 표시하는 try 및 catch 블록이 정의됩니다. 메인 함수에서 'for' 루프가 실행되고 'my_thread' 클래스의 newobject가 생성됩니다. 이 개체에서 '실행' 함수가 호출됩니다.