1,线程的状态
// 新建,还没有调用start()
NEW,
// 等待CPU调度执行
RUNNABLE,
// 等待进入monitor锁或调用了Object.wait()之后重新进入monitor锁
BLOCKED,
// 本线程调用了wait(),此时会释放monitor锁,需等待别的线程调用notify,或者notifyAll()
// 别的线程(join)加入并运行完毕之前所处状态,,此时会不会释放monitor锁。
// 线程进入等待状态(调用unsafe.park),需要unsafe.unpark唤醒,此时会不会释放monitor锁
WAITING,
// 调用了Thread.sleep,Object.wait(long),Thread.join(long),LockSupport.parkNanos,LockSupport.parkUntil等方法进入此状态
// 自然等待结束之后进入RUNNABLE状态
TIMED_WAITING,
// 线程执行完成或者被kill
TERMINATED;
2,状态流转图

3,Block举例:
wait:
public static void main(String[] args) {
Thread t1 =new Thread(() -> {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
}
synchronized (ThreadTest.class) {
System.out.println("I am trying to week up main thread");
ThreadTest.class.notify();
}
});
t1.start();
synchronized (ThreadTest.class) {
System.out.println("i'm waiting");
ThreadTest.class.wait();
System.out.println("i'm week up!");
}
}
运行结果:
i'm waiting
I am trying to week up main thread
i'm week up!
join:
public static void main(String[] args)throws InterruptedException {
Thread t1 =new Thread(() -> {
try {
Thread.sleep(2000L);
} catch (InterruptedException e) {
}
System.out.println("i am finished");
});
t1.start();
System.out.println("i'm waiting for t1");
t1.join();
System.out.println("now it's my turn");
}
运行结果:
i'm waiting for t1
i am finished
now it's my turn
park:
public static void main(String[] args) {
Thread t1 =new Thread(() -> {
System.out.println("i am running");
// 等待两秒
LockSupport.parkNanos(2000000000L);
System.out.println("i am run finished");
});
t1.start();
System.out.println("i'm main");
}
运行结果:
i'm main
i am running
i am run finished