一个线程只能有一次NEW状态和TERMINATED状态。
NEW(新建状态):创建后,启动前。线程就处于这个状态。
RUNNABLE(可运行状态):线程正在执行该方法(run方法)。线程就处于该状态。
BLOCKED(阻塞状态):一个线程获取synchornized锁对象失败。线程就处于该状态。
WAITING(等待状态):一个线程获取Lock锁对象失败,或者调用wait()。线程就处于该状态。
TIMED_WAITING(计时等待状态):线程正在执行sleep方法,或者wait(long mills)。线程就处于该状态。
TERMINATED(消亡状态):线程把任务执行完毕后。线程就处于该状态。
NEW(新建状态):
public class Test01 {
public static void main(String[] args) {
Thread t = new Thread();
State s = t.getState();
System.out.println("t的状态为:"+s);
}
}
//输出为:t的状态为: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(100);//保证线程已经启动,并开始执行run方法中的代码
State s = t.getState();
System.out.println("t的状态为:"+s);
}
}
//输出为:t的状态为:RUNNABLE
BLOCKED(阻塞状态):
public class Test05 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
synchronized(this) {
for(;;);
}
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
Thread.sleep(100);//保证两个线程都已经启动,并开始执行run方法
System.out.println("t1的状态为:"+t1.getState());
System.out.println("t2的状态为:"+t2.getState());
}
}
//输出结果:t1的状态为:RUNNABLE
// t2的状态为:BLOCKED
WAITING(等待状态):
public class Test06 {
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Runnable r = new Runnable() {
@Override
public void run() {
//上锁
lock.lock();
for(;;);
//lock.unlock();
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
Thread.sleep(100);//保证两个线程都已经启动,并开始执行run方法
System.out.println("t1的状态为:"+t1.getState());
System.out.println("t2的状态为:"+t2.getState());
}
}
//输出结果:t1的状态为:RUNNABLE
// t2的状态为:WAITING
TIMED_WAITING(计时等待状态):
public class Test04 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t = new Thread(r);
t.start();
Thread.sleep(100);//保证线程已经启动,并开始执行run方法中的代码
State s = t.getState();
System.out.println("t的状态为:"+s);
}
}
//输出结果:t的状态为:TIMED_WAITING
TERMINATED(消亡状态):
public class Test03 {
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);//保证线程已经启动,并把run方法中的代码执行完毕
State s = t.getState();
System.out.println("t的状态为:"+s);
}
}
//输出为:Thread-0
// t的状态为:TERMINATED



