> Java > java지도 시간 > 본문

자바 중단 예외

WBOY
풀어 주다: 2024-08-30 16:15:01
원래의
895명이 탐색했습니다.

InterruptedException은 스레드가 휴면 상태이거나 대기 중이거나 일부 활동이 실행되기 전이나 실행 중에 점유되어 중단될 때 발생합니다. 때때로 메소드는 현재 스레드가 중단되었는지 여부를 테스트하려고 할 수 있습니다. 중단된 경우 즉시 예외가 발생합니다. 그렇지 않으면 이전에 작동했던 방식대로 작동하게 됩니다. 이번 주제에서는 Java InterruptedException에 대해 알아보겠습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

구문

예외를 사용하려면 다음 구문을 사용해야 합니다.

if (Thread.interrupted ())  // Clears interrupted status!
throw new InterruptedException ();
로그인 후 복사

여기서 InterruptedException() 메소드는 자세한 메시지가 없는 InterruptedException을 매개변수로 생성합니다.

그러나 InterruptedException(String s)처럼 발생하면 특정 세부 정보가 포함된 InterruptedException이 생성됩니다. 이 방법에서는 s가 상세 메시지입니다.

Java에서 InterruptedException은 어떻게 작동하나요?

여기에서는 InterruptedException의 작업 흐름에 대해 논의합니다. 다중 스레드 코드에서는 스레드가 종종 차단될 수 있습니다. 스레드는 다음과 같은 외부 조건이 충족될 때까지 실행을 일시 중지합니다.

  • 잠금이 해제될 때
  • 또는 다른 스레드가 작업을 완료합니다
  • 또한 일부 I/O 작업이 완료됩니다

여기에서는 스레드가 중단될 수 있습니다. 인터럽트가 발생하면 스레드가 수행 중인 일반적인 작업을 중지합니다. 그러나 지정된 인터럽트에 대한 정확한 응답은 스레드의 상태와 스레드가 아래와 같이 구현되는 방식에 따라 달라집니다.

존재했던 스레드나 이전 스레드를 차단하는 데 사용할 수 있는 스레드가 있습니다. 이것이 발견되면 InterruptedException이 발생합니다. 문제가 없고 이전 스레드가 없으면 스레드는 작업을 계속합니다. 스레드가 예외를 발견하면 스레드의 중단 상태를 true로 설정합니다. 스레드는 정기적으로 checkInterrupted() 메소드를 폴링합니다. 이는 스레드가 작동할 것으로 예상되는 기본 방식입니다. 프로세스가 완료되면 정리 활동이 발생합니다. 정리 후에는 실행이 중지됩니다. InterruptedException이 발생하면 예외가 발생하고, 그렇지 않은 경우에는 정상적인 실행 흐름을 계속합니다.

위 프로세스에 중단이 발생하면 프로세스가 즉시 스레드를 닫아서는 안 됩니다. 이는 항상 발생하는 일부 계산이 진행 중이므로 기다려야 하기 때문입니다.

건축자

생성자는 새로 생성된 객체나 메소드를 초기화하는 데 도움이 되는 Java 객체입니다. 반환 유형이 없는 Java 인스턴스입니다. 이는 객체를 초기화해야 하므로 해당 객체가 속한 클래스와 동일한 이름을 갖습니다. 결과적으로 객체가 호출될 때마다 생성자가 자동으로 호출되어 초기화됩니다. 아래는 생성자 메소드입니다.

InterruptedException ()
로그인 후 복사

여기서 이 메소드는 메시지가 없는 예외를 생성합니다. InterruptedException 클래스의 인스턴스가 여기에 생성됩니다. 이 생성자에서는 메시지 매개변수가 null로 설정됩니다.

예:

public InterruptedException () InterruptedException (String s)
로그인 후 복사

InterruptedException 클래스의 이 메소드에서는 매개변수가 문자열 형식의 지정된 메시지로 사용됩니다. 여기서 문자열 매개변수는 오류를 발생시킨 클래스의 이름을 설명합니다.

InterruptedException 예시

이제 스레드가 중단되는 예를 살펴보겠습니다.

// Java Program to check how
// interrupt () method  works
// simultaneously while a thread stops working
class CheckInterruption extends Thread {
public void run ()
{
try {
Thread.sleep (2000);
System.out.println ( "We are checking Interrupted Exception");
}
catch (InterruptedException e) {
throw new RuntimeException ( "Thread is" + "interrupted");
}
}
public static void main (String args[])
{
CheckInterruption t1 = new CheckInterruption ();
t1.start ();
try {
t1.interrupt ();
}
catch (Exception e) {
System.out.println ("Exception handled");
}
}
}
로그인 후 복사

출력:

자바 중단 예외

위 코드는 Interrupted Exception의 개념을 이해하는 데 도움이 됩니다. Java의 Thread 클래스를 확장하는 CheckInterruption클래스가 있습니다. 그런 다음 try 블록에서 예외를 찾습니다. 예외가 발생하면 catch 블록에 catch되어 출력이 catch 블록으로 표시됩니다. 이는 중단이 포착되고 필요한 출력이 표시되는 예제의 경우입니다. 하지만 catch 블록이 Java에 있는 Exception() 메서드를 호출하므로 프로그램이 완료되지 않습니다. 이제 예외가 발생하고 다음 스레드가 시작되는 예를 확인해 보겠습니다.

class CheckInterruptingThread2 extends Thread{
public void run (){
try{  Thread.sleep (1000);
System.out.println ("task");
}catch (InterruptedException e){
System.out.println ("Exception is handled "+e);  }
System.out.println ("thread is now in running state...");
}
public static void main (String args[]){
CheckInterruptingThread2 t1=new CheckInterruptingThread2 ();
t1.start ();
t1.interrupt ();
}
}
로그인 후 복사

출력:

자바 중단 예외

The above program uses a class that is again extending the Thread class in Java. In the try () block, we make the thread sleep for some time, and then the catch block catches the exception when it is encountered. Once it is handled, the message is printed, and then the interrupt () method is called, after which the next thread moves to the running state. The same is displayed after the method call is finished and the thread starts working.

How to avoid InterruptedException?

The solution to this exception is you can stop making use of thread.sleep () method. Instead of this method, the more efficient method will be SystemClock.sleep () method. Another replacement for the above-mentioned method can be using TimeCOunter, which will depend on the logic and code where it is being used. This can also be an optimal solution.

If at all you would still like to make use of thread.sleep () then it should be used as below.

try {
Thread.sleep ();
} catch (InterruptedException e) {
Thread.currentThread ().interrupt (); /* this line will see to it that Thread.interrupted () always returns true */
throw new RuntimeException (e);
}
로그인 후 복사

Conclusion – Java InterruptedException

As the word exception suggests, it is a state which can be checked and allowed to pass in some cases. InterruptedException happens when a thread waits or sleeps, and other threads are interrupted and cannot proceed further. We can handle this exception by either using proper try-catch blocks or by avoiding the usage of the sleep () method.

위 내용은 자바 중단 예외의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!