Thread构造方法是如何生成默认线程名称的?
无参构造中调用init方法,init的第三个参数传的是一个字符串name,实参是"Thread-" + nextThreadNum()
,这个nextThreadNum()
方法返回的是一个int类型的整数,也就是调用一次num
加1。
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
private static int threadInitNumber;
private static synchronized int nextThreadNum() {
return threadInitNumber++;
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null);
}
init(ThreadGroup g, Runnable target, String name,long stackSize, AccessControlContext acc)
通过下面这句将name的值赋值给了成员变量name
this.name = name.toCharArray();
重写了init方法,多个一个参数AccessControlContext acc
。
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name.toCharArray();
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();
}
}
/* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess();
/*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
}
g.addUnstarted();
this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext =
acc != null ? acc : AccessController.getContext();
this.target = target;
setPriority(priority);
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize;
/* Set thread ID */
tid = nextThreadID();
}
如何设置线程名称和获取线程名称?
setName
设置线程名称名称,实质是给成员变量name
赋值
private volatile char name[];//Thread类的成员变量
public final synchronized void setName(String name) {
checkAccess();
this.name = name.toCharArray();//这里是将设置的name变成字符数组,为什么呢?
if (threadStatus != 0) {
setNativeName(name);
}
}
getName
是用String的带参构造方法把字符数组变成字符串name.
public final String getName() {
return new String(name, true);
}