>  기사  >  Java  >  Java의 ThreadGroup

Java의 ThreadGroup

王林
王林원래의
2024-08-30 16:07:45359검색

Java의 ThreadGroup은 하나의 단위로 작동하도록 생성된 스레드의 집합으로 정의할 수 있으며, Java의 ThreadGroup은 일반적으로 스레드 그룹에 대해 결합된 작업을 수행해야 할 때 사용됩니다. ThreadGroup은 여러 스레드를 관리하는 효율적인 방법을 제공합니다.

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

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

구문:

Java에서 ThreadGroup을 생성하고 사용하는 방법에 대한 구문은 다음과 같습니다.

package <packagename>;
public class <mainclassname>{
public static void main(String args[]){
// creating threadgroup object
ThreadGroup grp= new ThreadGroup(“<parent thread name>”);
// creating threads belonging to given thread group
<ThreadClassName> one =new <ThreadClassName>(“<threadname1>”, grp);
// creating first member of thread group
<ThreadClassName> two =new <ThreadClassName>(“<threadname2>”, grp);
// creating second member of thread group
}
}
class <ThreadClassName> extends Thread{
<ThreadClassName>(String threadName, ThreadGroup grp){
super(threadName,grp); // call to parent class constructor
start();      // start the thread
}
public void run(){
// implement required logic
}
}

위 구문에서는 ThreadGroup 인스턴스를 생성하고 스레드 그룹의 일부인 두 개의 스레드를 생성했습니다. 우리는 메인 클래스와 스레드 클래스인 <부모 스레드 이름> 상위 스레드 이름의 이름입니다.

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

  • 스레드 그룹은 여러 관련 스레드의 모음입니다. 스레드 그룹을 사용하면 개발자가 여러 Java 스레드를 동시에 처리할 수 있으며 java.lang 패키지에서 사용할 수 있습니다.
  • 내부적으로 스레드 그룹은 연결된 상위 스레드가 없는 상위 스레드를 제외하고 각 스레드에 상위 스레드가 있는 트리로 생각할 수 있습니다.
  • 특정 스레드 그룹에 속한 스레드는 해당 스레드가 속한 동일한 스레드 그룹에 대한 정보에 접근할 수 있다는 점에 유의하세요. 상위 스레드 그룹이나 다른 스레드 그룹에 대한 정보가 없습니다.

다음은 java.lang.ThreadGroup에서 사용할 수 있는 생성자에 대한 설명입니다.

Constructor Description
public ThreadGroup(String name) This constructor is used for creating a new thread group, the parent of this thread group is the same as the parent group of the currently executing thread. This constructor may throw SecurityException in case the currently running thread does not have permission to create a thread group.
public ThreadGroup(ThreadGroupparentgroup,String name) This constructor creates a thread group with a specified thread group as a parent and specified name. This constructor may throw NullPointerException in case the specified thread group is null, and SecurityException may be thrown in case the currently running thread does not have permission to create a thread group.
생성자

설명
Method Description
int activeCount() This method returns the number of active running threads available in a given thread group.
int activeGroupCount() This method returns the number of active thread groups running.
destroy() This method destroys the thread group and its sub groups if available.
int enumerate(Thread arr[]) Call to this method puts the thread available in invoking thread group into the group array of threads.
int enumerate(Thread arr[], boolean recurse) Call to this method puts the thread available in invoking thread group into the group array of threads; if the recursive flag is true, then threads in subgroups are also added to the group.
int enumerate(ThreadGroup[] thgrp) This method puts the subgroups of the invoking thread group into the thread group array.
int enumerate(ThreadGroup[] thgrp, boolean recursive) This method puts the subgroups of the invoking thread group into the thread group array; if the recursive flag is set to true, then all subgroups of subgroups are added to the group array.
공개 ThreadGroup(문자열 이름) 이 생성자는 새 스레드 그룹을 생성하는 데 사용되며, 이 스레드 그룹의 부모는 현재 실행 중인 스레드의 부모 그룹과 동일합니다. 현재 실행 중인 스레드에 스레드 그룹을 생성할 권한이 없는 경우 이 생성자는 SecurityException을 발생시킬 수 있습니다. 공개 ThreadGroup(ThreadGroupparentgroup,문자열 이름) 이 생성자는 지정된 스레드 그룹을 상위 및 지정된 이름으로 사용하여 스레드 그룹을 생성합니다. 이 생성자는 지정된 스레드 그룹이 null인 경우 NullPointerException이 발생할 수 있고, 현재 실행 중인 스레드에 스레드 그룹을 생성할 권한이 없는 경우 SecurityException이 발생할 수 있습니다.

다음은 java.lang.ThreadGroup에서 사용할 수 있는 몇 가지 중요한 메소드 목록입니다.

방법

설명

int activeCount() 이 메소드는 특정 스레드 그룹에서 사용 가능한 활성 실행 스레드 수를 반환합니다. int activeGroupCount() 이 메소드는 실행 중인 활성 스레드 그룹 수를 반환합니다. 파괴() 이 방법은 가능한 경우 스레드 그룹과 해당 하위 그룹을 파괴합니다. int enumerate(스레드 arr[]) 이 메소드를 호출하면 스레드 그룹을 호출하는 데 사용할 수 있는 스레드가 스레드 그룹 배열에 배치됩니다. int enumerate(스레드 arr[], 부울 재귀) 이 메소드를 호출하면 스레드 그룹을 호출하는 데 사용할 수 있는 스레드가 스레드 그룹 배열에 배치됩니다. 재귀 플래그가 true이면 하위 그룹의 스레드도 그룹에 추가됩니다. int enumerate(ThreadGroup[] thgrp) 이 메소드는 호출 스레드 그룹의 하위 그룹을 스레드 그룹 배열에 넣습니다. int enumerate(ThreadGroup[] thgrp, 부울 재귀) 이 메소드는 호출 스레드 그룹의 하위 그룹을 스레드 그룹 배열에 넣습니다. 재귀 플래그가 true로 설정되면 하위 그룹의 모든 하위 그룹이 그룹 배열에 추가됩니다.

위에 나열된 방법 외에도 필요에 따라 사용할 수 있는 다른 방법도 있습니다.

Java의 ThreadGroup 예

아래는 Java의 ThreadGroup 예입니다.

package com.educba.threadgroupdemo;
import java.lang.*;
class ThreadDemo extends Thread
{
ThreadDemo(String threadname, ThreadGroup thgrp)
{
super(thgrp, threadname);
start();
}
public void run()
{
// implement required logic inside run method
for (int i = 0; i < 2000; i++)
{
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
System.out.println("InterruptedException Exception encountered");
}
}
}
}
public class ThreadGroupDemo
{
public static void main(String args[])
{
// creating the thread group
ThreadGroup grp = new ThreadGroup("parent-thread");
// creating new thread and adding to thread group
ThreadDemo t1 = new ThreadDemo("first", grp);
System.out.println("Starting first thread");
// creating another thread and adding to thread group
ThreadDemo t2 = new ThreadDemo("two", grp);
System.out.println("Starting second thread");
// finding the number of active threads
System.out.println("Number of active threads running in thread group: "
+ grp.activeCount());
}
}
자바에서 스레드 그룹을 사용하는 방법을 살펴보겠습니다.

코드:

Java의 ThreadGroup

출력:

결론 위 기사는 Java에서 스레드 그룹의 작동을 명확하게 설명합니다. 이는 여러 스레드를 관리하는 내장된 방법입니다. 위에서 설명한 스레드 그룹 방법에 대한 Java 코드 예제는 Java 애플리케이션에서 사용됩니다.

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

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