>  기사  >  Java  >  Java에서 run() 메서드를 직접 호출하면 어떻게 되나요?

Java에서 run() 메서드를 직접 호출하면 어떻게 되나요?

PHPz
PHPz앞으로
2023-09-08 14:57:021365검색

Java에서 run() 메서드를 직접 호출하면 어떻게 되나요?

Thread 객체의 run() 메소드 를 직접 호출하면 별도의 스레드가 시작되지 않으며 현재 스레드 내에서 실행될 수 있습니다. 별도의 스레드에서 Runnable.run을 실행하려면 다음 중 하나를 수행합니다.

  • Runnable을 사용하여 Thread > 개체를 구성하고 Thread에서 start() 메서드를 호출합니다.
  • Thread 개체의 하위 클래스를 정의하고 해당 run() 메서드 정의를 재정의합니다. 그런 다음 해당 하위 클래스의 인스턴스를 생성하고 인스턴스의 start() 메서드를 직접 호출합니다.

Example

public class ThreadRunMethodTest {
   public static void main(String args[]) {
      MyThread runnable = new MyThread();
      runnable.run(); // Call to run() method does not start a separate thread
      System.out.println("Main Thread");
   }
}
class MyThread extends Thread {
   public void run() {
      try {
         Thread.sleep(1000);
      } catch (InterruptedException e) {
         System.out.println("Child Thread interrupted.");
      }
      System.out.println("Child Thread");
   }
}

위의 예에서 메인 스레드 ThreadRunMethodTest는 run() 메서드를 사용하여 하위 스레드 MyThread를 호출합니다. 이로 인해 나머지 메인 스레드가 실행되기 전에 하위 스레드가 완료되어 "Child Thread"가 "Main Thread"보다 먼저 인쇄됩니다.

출력

Child Thread
Main Thread

위 내용은 Java에서 run() 메서드를 직접 호출하면 어떻게 되나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제