2.Thread构造函数

  • Thread()
  • Thread(Runnable target)
  • Thread(Runnable target, String name)
  • Thread(String name)
  • Thread(Thread Group, Runnable target)
  • Thread(Thread Group, Runnable target , String namne)
  • Thread(Thread Group, Runnable target, String name, long stackSize)

线程的名字

由前的构造方法我们知道,在构造一个线程时,可以指定一个线程的名字,如果没有指定线程 的名字时,线程在初始化时会生成一个 Thread-数字 型的线程名称。

Thread的无参构造方法如下:

public Thread() {
    init(null, null, "Thread-" + nextThreadNum(), 0);
}

给线程命名:

public class ThreadConstruction {

    private final static String PREFIX = "ALEX=";

    public static void main(String[] args) {
        IntStream.range(0, 5).mapToObj(ThreadConstruction::createThread);
    }

    public static Thread createThread(final int intName) {
        return new Thread(() -> System.out.println(Thread.currentThread().getName()), PREFIX + intName);
    }
}

在线程启动之前,还有一个机会可以改名字,一旦线程启动, 名字将不再被修改。

线程的父子关系

  • 一个线程的创建肯定是由另一个线程完成的
  • 被创建线程的父线程是创建它的线程

Thread 与 ThreadGroup

如果在构造Thread的时候没有显示的指定一个ThreadGroup, 那么子线程将会被加入父线程所在的线程组

public class ThreadGroupConstruction {

    public static void main(String[] args) {

        Thread t1 = new Thread("t1");
        
        ThreadGroup group = new ThreadGroup("TestGroup");
        Thread t2 = new Thread(group,"t2");

        ThreadGroup mainThreadGroup = Thread.currentThread().getThreadGroup();
        System.out.println("Main thread belong group:" + mainThreadGroup);

        System.out.println("t1 and main belong the same group:" + (t1.getThreadGroup() == mainThreadGroup));

        System.out.println("t2 thread not belong main group:" + (t1.getThreadGroup() ==mainThreadGroup));

        System.out.println("t2 thread belong main TestGroup" + (group == t2.getThreadGroup()));
    }
}

打印如下:

Main thread belong group:java.lang.ThreadGroup[name=main,maxpri=10]
t1 and main belong the same group:true
t2 thread not belong main group:true
t2 thread belong main TestGrouptrue