线程的命名

先看下面这个例子:

关于Thread类的一些补充_构造方法

在​​已经介绍过了,还有另一种方式,可以先看看Thread类的构造方法:

关于Thread类的一些补充_优先级_02

也就是说如果我们是使用的继承Thread类的方式来创建线程的话就可以重写Thread类的这个方法给线程命名:

关于Thread类的一些补充_构造方法_03

关于初始化

上面在给线程命名的时候重写了Thread类的构造方法:

关于Thread类的一些补充_线程优先级_04

而在构造方法中有调用了一个init()方法:

关于Thread类的一些补充_构造方法_05

这个方法有很多参数。

ThreadGroup

用来对线程分组。可以将线程加到线程组中去。线程组是一个树状结构:

关于Thread类的一些补充_构造方法_06

肯定会有名称和上一级等属性。

Runnable

线程任务。

stackSize

关于Thread类的一些补充_线程优先级_07

就是说没指定就默认为0,开发者也不知道stackSize到底是用来干嘛的。

设置守护线程

可以使用setDaemon(true)

设置优先级

设置优先级可以使用setPriority(int newPriority)方法。

/**
* Changes the priority of this thread.
* <p>
* First the <code>checkAccess</code> method of this thread is called
* with no arguments. This may result in throwing a
* <code>SecurityException</code>.
* <p>
* Otherwise, the priority of this thread is set to the smaller of
* the specified <code>newPriority</code> and the maximum permitted
* priority of the thread's thread group.
*
* @param newPriority priority to set this thread to
* @exception IllegalArgumentException If the priority is not in the
* range <code>MIN_PRIORITY</code> to
* <code>MAX_PRIORITY</code>.
* @exception SecurityException if the current thread cannot modify
* this thread.
* @see #getPriority
* @see #checkAccess()
* @see #getThreadGroup()
* @see #MAX_PRIORITY
* @see #MIN_PRIORITY
* @see ThreadGroup#getMaxPriority()
*/
public final void setPriority(int newPriority) {
ThreadGroup g;
checkAccess();
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);
}
}

 最小值是1,最大值是10,默认是5:

关于Thread类的一些补充_构造方法_08

线程优先级不能作为程序正确性的依赖,因为操作系统可以完全不用理会Java线程对于优先级的设定。理论上是优先级比较高的线程会获取优先被CPU调度的机会,但是事实上往往并不会如你所愿。 所以,不要在程序设计当中企图使用线程优先级绑定某些特定的业务,或者让业务严重依赖于线程优先级,这可能会让你大失所望。一般也很少设置线程的优先级,如果有需要,设置线程优先级时,针对频繁阻塞(休眠或者I/O操作)的线程需要设置较高优先级,而偏重计算(需要较多CPU时间或者偏运算)的线程则设置较低的优先级,确保处理器不会被独占。