>Java >java지도 시간 >Java의 하위 스레드에서 발생한 예외를 어떻게 처리할 수 있습니까?

Java의 하위 스레드에서 발생한 예외를 어떻게 처리할 수 있습니까?

Barbara Streisand
Barbara Streisand원래의
2024-12-05 16:37:19860검색

How Can I Handle Exceptions Thrown from Child Threads in Java?

스레드에서 발생한 예외 처리

멀티 스레드 애플리케이션에서는 기본 스레드의 하위 스레드에서 발생한 예외를 처리하는 것이 중요합니다. 다음 시나리오를 고려하십시오.

<br>public class Test extends Thread {<br> public static void main(String[] args) throws InterruptedException {</p>
<pre class="brush:php;toolbar:false">Test t = new Test();

try {
  t.start();
  t.join();
} catch (RuntimeException e) {
  System.out.println("** RuntimeException from main");
}

System.out.println("Main stoped");

}

@Override
public void run() {

try {
  while (true) {
    System.out.println("** Started");

    sleep(2000);

    throw new RuntimeException("exception from thread");
  }
} catch (RuntimeException e) {
  System.out.println("** RuntimeException from thread");

  throw e;
} catch (InterruptedException e) {

}

}
}

이 예에서는 하위 스레드에서 발생한 예외가 기본 스레드로 전파되지 않습니다. 이는 Java가 스레드에서 발생한 예외를 기본 스레드의 핸들러와 자동으로 연결하지 않기 때문입니다.

해결책: Thread.UncaughtExceptionHandler

스레드에서 예외를 처리하려면 다음 중 하나를 수행하세요. Thread.UncaughtExceptionHandler를 사용할 수 있습니다. 이 인터페이스는 스레드에서 포착되지 않은 예외가 발생할 때 호출되는 uncaughtException() 메서드를 제공합니다.

Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
  @Override
  public void uncaughtException(Thread th, Throwable ex) {
    System.out.println("Uncaught exception: " + ex);
  }
};
Thread t = new Thread() {
  @Override
  public void run() {
    System.out.println("Sleeping ...");
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      System.out.println("Interrupted.");
    }
    System.out.println("Throwing exception ...");
    throw new RuntimeException();
  }
};
t.setUncaughtExceptionHandler(h);
t.start();

uncaughtExceptionHandler를 스레드에 설정하면 포착되지 않은 모든 예외가 제공된 구현에 의해 처리됩니다. 이를 통해 메인 스레드가 예외를 적절하게 캡처하고 처리하여 적절한 처리 및 오류 보고를 보장합니다.

위 내용은 Java의 하위 스레드에서 발생한 예외를 어떻게 처리할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.