一:默认构造函数 Thread()
1.在用默认构造函数创建线程的时候,会有一个默认的线程名“thread-0”,随着线程创建的增加名称会递增;thread-0 thread-1...... 。Thread源码:
/** * Allocates a new {@code Thread} object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * {@code (null, null, 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. */ public Thread() { init(null, null, "Thread-" + nextThreadNum(), 0); }
2.默认构造函数如果不复写run方法,那么将不会有逻辑单元执行。逻辑单元也就是run方法里面的代码。Thread的源码:
/** * If this thread was constructed using a separate * <code>Runnable</code> run object, then that * <code>Runnable</code> object's <code>run</code> method is called; * otherwise, this method does nothing and returns. * <p> * Subclasses of <code>Thread</code> should override this method. * * @see #start() * @see #stop() * @see #Thread(ThreadGroup, Runnable, String) */ @Override public void run() { if (target != null) { target.run(); } }
3.默认构造函数的线程组(ThreadGroup)为空,所以Thread类会为创建的线程指定父线程组(ThreadGroup)。如果调用构造方法的是main方法,那么父线程组就是main线程组。Thread源码:
Thread parent = currentThread(); SecurityManager security = System.getSecurityManager(); if (g == null) { /* Determine if it's an applet or not */ /* If there is a security manager, ask the security manager what to do. */ if (security != null) { g = security.getThreadGroup(); } /* If the security doesn't have a strong opinion of the matter use the parent thread group. */ if (g == null) { g = parent.getThreadGroup(); } }
g就是线程组。
二:自定义线程名称的构造函数 Thread("threadName")
1.调用该构造函数可以为线程指定线程名称。Thread源码:
/** * Allocates a new {@code Thread} object. This constructor has the same * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread} * {@code (null, target, name)}. * * @param target * the object whose {@code run} method is invoked when this thread * is started. If {@code null}, this thread's run method is invoked. * * @param name * the name of the new thread */ public Thread(Runnable target, String name) { init(null, target, name, 0); }
2.其余特点与默认构造方法一样
三:带Runnable接口构造函数Thread(Runnable target);
该构造函数适用于选择模式,也就是将run方法的逻辑单元抽出来形成一个接口