Tag - thread

J.A.R.V.I.S

Life is not just Live

2019

JAVA线程

基础概念

线程的所有状态:

这些状态都在 Thread中的State枚举中定义:

1
2
3
4
5
6
7
8
9
10
11
12
13
public enum State {
//表示刚刚创建的线程,这种线程还没开始执行
NEW,
//在 start() 方法调用后,线程开始执行,此时状态处于 RUNABLE
RUNNABLE,
//如果线程在执行过程中遇到 synchronized 同步块,就会进入 BLOCKED 阻塞状态,直到获取请求的锁
BLOCKED,
//等待状态,WAITING 会无时间限制的等待,TIMED_WAITING 会有时间限制
WAITING,
TIMED_WAITING,
//线程执行完毕,表示结束
TERMINATED;
}

初始线程

  1. Thread

  2. Runable接口

    Thread类中调用start()方法之后会让线程执行run()方法,而run()方法中又是对Runable实例的调用

    1
    2
    3
    4
    5
    6
    7
    8
    9
     /* What will be run. */
    private Runnable target;

    @Override
    public void run() {
    if (target != null) {
    target.run();
    }
    }

9月 22 · 25 min

0 %