线程生命周期
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
public enum State {
/**
* Thread state for a thread which has not yet started.
*/
NEW,
/**
* Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.
*/
RUNNABLE,
/**
* Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@link Object#wait() Object.wait}.
*/
BLOCKED,
/**
* Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
* <ul>
* <li>{@link Object#wait() Object.wait} with no timeout</li>
* <li>{@link #join() Thread.join} with no timeout</li>
* <li>{@link LockSupport#park() LockSupport.park}</li>
* </ul>
*
* <p>A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called <tt>Object.wait()</tt>
* on an object is waiting for another thread to call
* <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
* that object. A thread that has called <tt>Thread.join()</tt>
* is waiting for a specified thread to terminate.
*/
WAITING,
/**
* Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
* <ul>
* <li>{@link #sleep Thread.sleep}</li>
* <li>{@link Object#wait(long) Object.wait} with timeout</li>
* <li>{@link #join(long) Thread.join} with timeout</li>
* <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
* <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
* </ul>
*/
TIMED_WAITING,
/**
* Thread state for a terminated thread.
* The thread has completed execution.
*/
TERMINATED;
}
|

在 Thread 类中,有如下常用的方法:

线程优先级
线程调度方式
- 抢占式调度:多个线程抢夺 CPU 的执行权,CPU 在什么时候执行哪条线程是不确定的,执行多长时间也是不确定的,所以抢占式调度它体现了一个随机性。
- 非抢占式调度 / 分时调度模型:所有线程轮流使用 CPU 的使用权,平均分配每个线程占用 CPU 的时间片 。
在 Java 当中,它采取了第一种抢占式调度模型的方式。
在 Thread 类中,最小优先级是 1,最大是 10,默认为 5,优先级越高,该线程抢到 cpu 执行权的机会越大(注意是机会很大,不是 100%)

守护线程
守护线程又叫备胎线程,通过 setDaemon()方法把当前线程设置为守护线程。
- 当仅剩的线程是非守护线程时,该线程会继续执行,当仅剩的线程是守护线程时,Java 虚拟机将直接退出
- 注意:setDaemon(true)方法必须在 start()方法前执行,否则会抛出 ILLegalThreadStateException 异常。
- 在守护线程中产生的新线程也是守护线程。
应用场景:在 QQ 聊天界面传输文件,如果在文件未传输完的情况下退出界面,那么文件就会传输中止
礼让线程
通过 yield()方法,当前线程将让出当前线程的执行权
插入线程
通过 join()方法,可以在线程 A 执行的时候,让线程 B 插队,等线程 B 执行完再执行线程 A,或者调用 join 方法时传入毫秒时间,让线程 B 插队的时间受控