大致分为六个状态分别为:
1.NEW(新建状态):创建后,启动前。
2.RUNNABLE(可运行状态):线程正在执行代码。
3.BLOCKED(阻塞状态):一个线程获取synchronized锁对象失败。
4.WAITING(无线等待):一个线程获取lock锁对象失败;或调用wait方法。
5.TIMED_WAITING(计时等待状态):线程正在执行sleep方法。
6.TERMINATED(消亡状态):线程把任务执行完毕后。
注:一个线程只有一次NEW状态和TERMINATED状态。
举例:
(1).NEW(新建状态):
public class Test01 {
public static void main(String[] args) {
Thread t = new Thread();
State s = t.getState();
System.out.println(s);//状态为NEW
}
}
(2).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(s);//状态为RUNNABLE
}
}
(3).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.getState());//状态为RUNNABLE
System.out.println(t2.getState());//状态为BLOCKED
}
}
(4).WAITING(无线等待):
A.获取lock对象失败
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.getState());//状态为RUNNABLE
System.out.println(t2.getState());//状态为WAINTING
}
}
B.调用wait方法
public class Test07 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
method();
}
};
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
Thread.sleep(100);//保证两个线程都已经启动,并开始执行run方法
System.out.println(t1.getState());//状态为WAITING
System.out.println(t2.getState());//状态为WAITING
}
public static synchronized void method() {
//String str = "";
//获取当前类的反射对象
Class c = Test07.class;
try {
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
(5).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(s);//状态为TIMED_WAITING
}
}
(6).TERMINATED(消亡状态):
public class Test6 {
public static void main(String[] args) throws InterruptedException {
Runnable r = new Runnable() {
@Override
public void run() {
}
};
Thread t = new Thread(r);
t.start();
Thread.sleep(1000);//保证线程已经启动,并把run方法中的代码执行完毕
State s = t.getState();
System.out.println(s);//状态为TERMINATED
}
}