构造Thread对象
如下代码创建并打印Thread对象的名称
public class CreateThread {
public static void main(String[] args) {
Thread t = new Thread();
Thread t1 = new Thread();
t.start();
t1.start();
System.out.println(t.getName());
System.out.println(t1.getName());
}
结果为
Thread-0
Thread-1
通过查看源码发现
/**
* Allocates a new {@code Thread} object. This constructor has the same
* effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
* {@code (null, target, gname)}, where {@code gname} is a newly generated
* name. Automatically generated names are of the form
* {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
*
* @param target
* the object whose {@code run} method is invoked when this thread
* is started. If {@code null}, this classes {@code run} method does
* nothing.
*/
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
/* For autonumbering anonymous threads. */
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
public class ThreadCreate {
public static void main(String[] args) {
Thread t = new Thread();
t.start();
System.out.println(t.getThreadGroup());
System.out.println(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getThreadGroup().getName());
}
}
java.lang.ThreadGroup[name=main,maxpri=10]
main
main
- 如果创建Thread时没有指定名称,将会默认以Thread-开头,从0开始计数
- 如果在构造Thread的时候没有传递或者没有覆写run方法,改Thread将不会调用任何东西,如果传递了Runnable接口实例或者覆写了Thread的run方法,则会执行该逻辑单元
- 如果构造线程对象时未传入ThreadGroup,则Thread会默认获取父线程的ThreadGroup作为该线程的ThreadGroup
- 构造Thread的时候传入stacksize代表该线程占用stack大小,如果没有指定,默认是0,0代表会忽略该参数该参数会被JNI函数去使用