getThreadGroup()
包java.lang.Thread.getThreadGroup()中提供了此方法。
此方法用于返回该线程的ThreadGroup [即,它表示该线程基本上属于哪个ThreadGroup]。
此方法是最终方法,因此我们不能在子类中覆盖此方法。
该方法的返回类型为ThreadGroup,因此它返回该线程的Threadgroup,这意味着我们的线程基本上属于哪个组。
此方法不会引发任何异常。
语法:
final ThreadGroup getThreadGroup(){ }
参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
该方法的返回类型为ThreadGroup,它返回此线程的ThreadGroup。
getThreadGroup()
方法示例/* We will use Thread class methods so we are importing the package but it is not mandate because it is imported by default */ import java.lang.Thread; class GetThreadGroup extends Thread { //覆盖run()Thread类 public void run() { System.out.println("We are in run() method"); } } class Main { public static void main(String[] args) { //创建一个GetThreadGroup类的对象 GetThreadGroup gt_group = new GetThreadGroup(); //我们正在创建ThreadGroup类的对象 ThreadGroup tg1 = new ThreadGroup("ThreadGroup 1"); ThreadGroup tg2 = new ThreadGroup("ThreadGroup 2"); //我们正在创建Thread类的对象,然后 //我们正在分配两个线程的ThreadGroup- Thread th1 = new Thread(tg1, gt_group, "First Thread"); Thread th2 = new Thread(tg2, gt_group, "Second Thread"); //start()具有Thread类的Thread类对象的调用方法 th1.start(); th2.start(); //这里我们显示的是哪个线程 //属于哪个组 System.out.println("The " + th1.getName() + " " + "is belongs to" + th1.getThreadGroup().getName()); System.out.println("The " + th2.getName() + " " + "is belongs to" + th2.getThreadGroup().getName()); } }
输出结果
E:\Programs>javac Main.java E:\Programs>java Main The First Thread is belongs toThreadGroup 1 We are in run() method We are in run() method The Second Thread is belongs toThreadGroup 2