JAVA的6中线程状态
1. NEW : 线程刚刚创建,还没有启动
2. RUNNABLE : 可运行状态,由线程调度器可以安排执行
* 包括READY和RUNNING两种细分状态
3. WAITING: 等待被唤醒
4. TIMED WAITING: 隔一段时间后自动唤醒
5. BLOCKED: 被阻塞,正在等待锁
6. TERMINATED: 线程结束
package com.example.demo.manytread;
public class SleepHelper {
public static void sleepSeconds(int seconds){
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.example.demo.manytread;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
public class T04_ThreadState {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("2: " + this.getState());
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(i + " ");
}
System.out.println();
}
}
public static void main(String[] args) throws Exception {
Thread t1 = new MyThread();
System.out.println("1: " + t1.getState());
t1.start();
t1.join();
System.out.println("3: " + t1.getState());
Thread t2 = new Thread(() -> {
try {
LockSupport.park();
System.out.println("t2 go on!");
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t2.start();
TimeUnit.SECONDS.sleep(1);
System.out.println("4: " + t2.getState());
LockSupport.unpark(t2);
TimeUnit.SECONDS.sleep(1);
System.out.println("5: " + t2.getState());
final Object o = new Object();
Thread t3 = new Thread(()->{
synchronized (o) {
System.out.println("t3 得到了锁 o");
}
});
new Thread(()-> {
synchronized (o) {
SleepHelper.sleepSeconds(5);
}
}).start();
SleepHelper.sleepSeconds(1);
t3.start();
SleepHelper.sleepSeconds(1);
System.out.println("6: " + t3.getState());
}
}
//输出结果
1: NEW
2: RUNNABLE
0 1 2 3 4 5 6 7 8 9
3: TERMINATED
4: WAITING
t2 go on!
5: TIMED_WAITING
6: BLOCKED
t3 得到了锁 o