>  기사  >  Java  >  Java의 데몬 스레드

Java의 데몬 스레드

WBOY
WBOY원래의
2024-08-30 16:03:14429검색

Java의 데몬 스레드는 우선순위가 가장 낮은 스레드로, 스레드에 서비스를 제공하는 데 사용되며, 이후 백그라운드 작업을 수행하는 데 사용됩니다. 백그라운드에서 수행되는 작업에는 가비지 수집과 종료 후 동시에 실행 시 자신을 방지하기 위해 JVM과 관련된 더 많은 작업이 포함됩니다. JVM(Java Virtual Machine)은 실제로 데몬 스레드가 아닌 다른 사용자 스레드를 찾으면 자체적으로 종료됩니다. Java Virtual Machine이 데몬 스레드를 발견한 경우 해당 스레드를 먼저 종료한 다음 자체적으로 종료됩니다.

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

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

구문

데몬 스레드에 대한 특정 구문은 없지만 다음과 같이 표시되는 데몬 스레드의 일부로 다른 방법으로 생성 및 호출할 수 있습니다.

public class DaemonThread extends Thread
  • 공개 클래스: 클래스의 액세스 한정자는 공개이며
  • DaemonThread: 스레드 유형은 DaemonThread이므로 Thread 클래스에서 상속 및 확장됩니다.
  • 스레드: 스레드 클래스는 Thread 클래스의 속성을 데몬 스레드에 상속하는 데 사용됩니다.

또한 데몬 스레드를 호출하기 위한 구문이 다른 다양한 메서드가 포함됩니다.

public final void setDaemon(boolean on)

이 메소드 구문은 데몬 스레드가 true를 의미하는 부울로 표시될 때 스레드가 데몬 스레드이기 때문에 매개변수를 부울로 전달합니다.

public final boolean isDaemon()

이 메소드는 발견된 스레드가 데몬 스레드인 경우 true를 반환하고, 발견된 스레드가 false인 경우 false를 반환합니다.

데몬 스레드는 Java에서 어떻게 작동하나요?

데몬 스레드는 스레드를 생성하는 데 사용되는 스레드이며 상위 스레드로부터 모든 속성을 상속받습니다. 따라서 기본 메서드 내에 존재하는 모든 스레드를 자식 메서드라고 하며, 부모 클래스의 실행 및 작업 수행을 위한 대부분의 속성을 상속합니다. 데몬이 아닌 스레드라고도 합니다.

여기에는 스레드를 데몬 스레드로 설정하기 위한 모든 메서드를 호출하여 데몬이 아닌 스레드나 사용자 스레드를 데몬 스레드로 만드는 실제 그림이 나와 있습니다. 실행 가능한 인터페이스도 확장되는 클래스인 Thread 클래스의 setDaemon() 메소드를 사용하여 데몬 스레드로 쉽게 설정할 수 있습니다.

유념해야 할 매우 중요한 점 중 하나는 JVM이 시작될 때마다 main이라는 스레드가 생성되고 이 시점에서 모든 프로그램이 실행되거나 시작된다는 것입니다. 실행 흐름이 시작되는 지점입니다. 기본적으로 모든 스레드는 새 스레드가 시작될 때까지 이 기본 스레드에서 실행됩니다. 새 스레드가 시작되는 경우 하위 스레드가 새 메소드 생성을 담당합니다.

그런 다음 setDaemon 메소드와 같은 메소드를 포함하는 데몬 스레드 생성 및 결정을 담당하는 메소드가 나옵니다. 이 메소드는 메소드에 전달된 매개변수 값에 따라 생성된 스레드가 데몬 스레드인지 비데몬 스레드인지를 결정합니다.

반면 공개 부울 스레드 isDaemon()은 반환 유형에 따라 스레드의 상태를 확인하는 데 사용됩니다. false인 경우 스레드는 데몬이 아닙니다. 그렇지 않으면 데몬입니다.

방법

아래에 언급된 방법은 다음과 같습니다

1. public void setDaemon(부울 상태)

이 메서드는 현재 스레드 실행을 전달된 매개변수에 따라 데몬 스레드로 만드는 데 사용됩니다. 전달된 매개변수가 부울이면 스레드는 데몬 스레드이고, 전달된 매개변수가 부울이 아니면 스레드는 데몬 스레드가 아닙니다. .

또한 IllegalThreadStateException 또는 보안 예외와 같은 보류 예외도 포착합니다. 불법ThreadStateException을 포착하기로 결정된 경우 스레드가 활성 상태여야 한다는 것이 전제 조건입니다. 현재 스레드를 수정할 수 없는 경우 보안 예외가 사용됩니다.

2. 공개 부울 isDaemon()

이 방법은 현재 상황을 확인하거나 반환 유형에 따라 현재 상태를 말하는 데 사용됩니다. 반환 유형이 true이면 데몬 스레드입니다. 그렇지 않으면 데몬이 아닌 스레드입니다.

Java의 데몬 스레드 예시

아래에 언급된 예는 다음과 같습니다.

예시 #1

이 프로그램은 void setDaemon(boolean status)을 사용하여 추가 조작을 위해 스레드를 데몬 스레드로 설정하는 방법과 스레드 세트가 데몬 스레드인지 또는 데몬 스레드인지를 나타내는 데몬 스레드를 식별한 후 isDaemon() 메서드를 한 번 호출하는 방법을 보여줍니다. 매개변수에 대한 부울 값으로 설정된 매개변수에 따라 데몬이 아닌 스레드.

코드:

public class Daemon_Thread_Demo_set extends Thread {
public Daemon_Thread_Demo_set(String nm){
super(nm);
}
public void run()
{
if(Thread.currentThread().isDaemon())
{
System.out.println("Current_Thread is a Daemon thread" + Thread.currentThread().getName());
}
else
{
System.out.println("Current thread is a non-daemon thread. "+ Thread.currentThread().getName());
}
}
public static void main(String[] args) {
Daemon_Thread_Demo_set nm1 = new Daemon_Thread_Demo_set("nm1");
Daemon_Thread_Demo_set nm2 = new Daemon_Thread_Demo_set("nm2");
Daemon_Thread_Demo_set nm3 = new Daemon_Thread_Demo_set("nm3");
nm1.setDaemon(true);
nm1.start();
nm2.start();
nm3.setDaemon(false);
nm3.start();
}
}

출력:

Java의 데몬 스레드

Example #2

This program demonstrates the illegal exceptions which are thrown once the current thread is identified as the Daemon thread but then the value when the set is not coming out to be set value matched with the thread it will be throwing the illegal exception as represented in the output.

Code:

public class Daemon_thrd_demo2 extends Thread {
public void run()
{
System.out.println("Current_thread_Name: "+Thread.currentThread().getName());
System.out.println("thread_as_Daemon"+Thread.currentThread().isDaemon());
}
public static void main(String[] args) {
Daemon_thrd_demo2 tst1 = new Daemon_thrd_demo2();
Daemon_thrd_demo2 tst2 = new Daemon_thrd_demo2();
tst1.start();
tst1.setDaemon(true);
tst2.start();
}
}

Output:

Java의 데몬 스레드

Note: The above program gives the Exception because the user thread should be set as a daemon thread only before calling the setDaemon() method. If it is not called in this way, then the thread after invocation will throw these exceptions while execution. Also, all non-daemon thread and daemon thread should be set up keeping in mind the place, i.e. before the child class or before the parent class.

Conclusion

Daemon thread and non-daemon thread have differences in them. It is very important to identify these differences as it can lead to conflicts and exception because daemon thread is a kind of thread that has the lowest priority compared to other threads while execution.

위 내용은 Java의 데몬 스레드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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