Java中线程的状态分为6种
分别是:
新建状态(NEW)
public class Test01 {
public static void main(String[] args) {
Thread t = new Thread();
State s = t.getState();
System.out.println(s); //NEW
}
}
可运行状态(RUNNABLE)
public class Test02 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
for(;;);
}
};
Thread t = new Thread(r);
t.start();
Thread.sleep(1000);//100毫秒保证子线程开始执行for(;;);这一行代码了
System.out.println(t.getState()); //RUNNABLE
}
}
阻塞状态(BLOCKED)
public class Test03 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized(this) {
for(;;);
}
}
};
Thread t1 = new Thread(r);
t1.start();
Thread t2 = new Thread(r);
t2.start();
Thread.sleep(100);//100毫秒保证两个子线程已经启动,并开始执行代码了
//获取并打印线程的状态
System.out.println(t1.getState());
System.out.println(t2.getState());
}
}
无限等待状态(WAITING)
public class Test04 {
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Runnable r = new Runnable() {
@Override
public void run() {
lock.lock();
for(;;);
}
};
Thread t1 = new Thread(r);
t1.start();
Thread t2 = new Thread(r);
t2.start();
Thread.sleep(100);//100毫秒保证两个子线程已经启动,并开始执行代码了
//获取并打印线程的状态
System.out.println(t1.getState());
System.out.println(t2.getState());
}
}
限时等待状态(TIMED_WAITING)
public class Test05 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(r);
t.start();
Thread.sleep(100);//100毫秒保证子线程开始执行Thread.sleep(1000000);这一行代码了
//获取并打印线程的状态
System.out.println(t.getState());
}
}
消亡状态(TERMINATED)
public class Test06 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
Thread t = new Thread(r);
t.start();
Thread.sleep(1000);//1000毫秒子线程一定把任务执行完毕了
//获取并打印线程的状态
System.out.println(t.getState());
}
}
1. 新建状态((NEW):新创建了一个线程对象,但还没有调用start()方法。
2. 可运行状态(RUNNABLE):正在执行run方法
3. 阻塞状态BLOCKED):表示线程阻塞于锁。
4. 无限等待状态(WAITING):进入该状态的线程需要等待其他线程做出一些特定动作(通知或中断)。
5. 限时等待状态(TIMED_WAITING):该状态不同于WAITING,它可以在指定的时间后自行返回。
6. 消亡状态(TERMINATED):表示该线程已经执行完毕。