logo

Java 실행 가능 인터페이스

java.lang.실행 가능 인스턴스가 스레드에 의해 실행되도록 의도된 클래스에 의해 구현되는 인터페이스입니다. 새로운 스레드를 시작하는 방법에는 하위 클래스 스레드와 Runnable 구현이라는 두 가지 방법이 있습니다. 스레드만 재정의하여 작업을 수행할 수 있는 경우 스레드를 하위 클래스로 분류할 필요가 없습니다. 달리다() Runnable의 메소드. 

Runnable을 사용하여 새 스레드를 생성하는 단계 

  1. Runnable 구현자를 만들고 run() 메서드를 구현합니다. 
  2. Thread 클래스를 인스턴스화하고 구현자를 Thread에 전달합니다. Thread에는 Runnable 인스턴스를 허용하는 생성자가 있습니다.
  3. Thread 인스턴스 start의 start()를 호출하면 내부적으로 구현자의 run()이 호출됩니다.
    • start()를 호출하면 run()에 작성된 코드를 실행하는 새 스레드가 생성됩니다.
    • run()을 직접 호출하면 동일한 스레드에서 실행될 새 스레드가 생성 및 시작되지 않습니다.
    • 새로운 실행 행을 시작하려면 스레드에서 start()를 호출하십시오. 

예:

java
// Runnable Interface Implementation public class Geeks  {  private class RunnableImpl implements Runnable   {  // Overriding the run Method  @Override  public void run()  {  System.out.println(Thread.currentThread().getName()  + ' executing run() method!');  }  }     // Main Method  public static void main(String[] args)   {   System.out.println('Main thread is: '  + Thread.currentThread().getName());    // Creating Thread  Thread t1 = new Thread(new Geeks().new RunnableImpl());    // Executing the Thread  t1.start();  } } 

산출
Main thread is: main Thread-0 executing run() method! 

설명: 출력에는 프로그램에 두 개의 활성 스레드가 표시됩니다. 메인 스레드와 Thread-0 기본 메소드는 메인 스레드에 의해 실행되지만 RunnableImpl에서 시작을 호출하면 새로운 스레드인 Thread-0이 생성되고 시작됩니다.



자바의 수학적 방법

Runnable에서 예외 처리

실행 가능 인터페이스는 확인된 예외를 발생시킬 수 없지만 run()에서 RuntimeException을 발생시킬 수 있습니다. JVM이 예외를 처리하거나 포착할 수 없는 경우 포착되지 않은 예외는 스레드의 예외 핸들러에 의해 처리되며 스택 추적을 인쇄하고 흐름을 종료합니다. 

예:

텍스트 감싸기용 CSS
java
// Checking Exceptions in Runnable Interface import java.io.FileNotFoundException; public class Geeks {  private class RunnableImpl implements Runnable   {  // Overriding the run method   @Override  public void run()  {  System.out.println(Thread.currentThread().getName()  + ' executing run() method!');    // Checked exception can't be thrown Runnable must  // handle checked exception itself  try {  throw new FileNotFoundException();  }  catch (FileNotFoundException e) {  System.out.println('Must catch here!');  e.printStackTrace();  }  int r = 1 / 0;    // Below commented line is an example  // of thrown RuntimeException.    // throw new NullPointerException();  }  }    public static void main(String[] args)  {  System.out.println('Main thread is: ' +  Thread.currentThread().getName());     // Create a Thread  Thread t1 = new Thread(new Geeks().new RunnableImpl());    // Running the Thread  t1.start();  } } 

산출:

Thread-0 executing run() method!  
Must catch here!
java.io.FileNotFoundException
at RunnableDemo$RunnableImpl.run(RunnableDemo.java:25)
at java.lang.Thread.run(Thread.java:745)
Exception in thread 'Thread-0' java.lang.ArithmeticException: / by zero
at RunnableDemo$RunnableImpl.run(RunnableDemo.java:31)
at java.lang.Thread.run(Thread.java:745)

설명 : 출력은 Runnable이 확인된 예외를 발생시킬 수 없음을 보여줍니다. FileNotFoundException 이 경우 호출자는 run()에서 확인된 예외를 처리해야 하지만 RuntimeException(발생 또는 자동 생성)은 JVM에 의해 자동으로 처리됩니다.

퀴즈 만들기