一、异常定义
IllegalThreadStateException是Java中一个线程异常。当尝试在不该启动的线程上调用start()方法,或在已经停止的线程上调用resume()方法时,将抛出IllegalThreadStateException。
二、异常原因
IllegalThreadStateException异常的出现是由于Java线程的状态不正确而导致的。请参考下面的代码:
Thread thread = new Thread();
thread.start();
// 状态1:线程已启动,但未进入可运行状态
if(thread.getState() == Thread.State.NEW) {
try {
thread.start();
} catch (IllegalThreadStateException e) {
System.out.println("线程未进入可运行状态");
}
}
// 状态2:线程已运行,但未调用wait()或sleep()
if(thread.getState() == Thread.State.RUNNABLE) {
try {
thread.start();
} catch (IllegalThreadStateException e) {
System.out.println("线程已经启动");
}
}
// 状态3:线程已经停止
if(thread.getState() == Thread.State.TERMINATED) {
try {
thread.resume();
} catch (IllegalThreadStateException e) {
System.out.println("线程已经停止");
}
}
三、异常解决
避免IllegalThreadStateException的方法有以下几点:
1、在启动线程之前,确保线程已经进入可运行状态。
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 线程需要执行的代码
}
});
thread.start();
2、在重复启动线程前,确保线程已经停止。
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 线程需要执行的代码
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.start();
3、避免使用suspend()和resume()方法。
下面的代码演示了为何不使用suspend()和resume()方法,这将导致线程无法停止:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程启动");
while (true) {
// 死循环
}
}
});
thread.start();
Thread.sleep(1000);
thread.suspend();
Thread.sleep(1000);
thread.resume(); // 线程无法停止
四、异常案例
下面的代码演示了IllegalThreadStateException异常的出现:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程启动");
}
});
thread.start();
thread.start(); // IllegalThreadStateException异常
五、异常总结
IllegalThreadStateException是Java线程中的一个异常,当线程状态不正确时会出现该异常。避免出现该异常的方式有:确保线程已经进入可运行状态、确保线程已经停止以及避免使用suspend()和resume()方法。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/243951.html
微信扫一扫
支付宝扫一扫