背景
在执行单元测试的时候,发现同一线程运行多次后,就会报一个线程的错误:
Exception in thread "Main Thread" java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:595) at thread.ThreadTest.main(ThreadTest.java:19) |
但是如果仅调用一次该线程的start()方法的时候,就不会报错
问题解析
在thread.start()查询源码后发现,在线程开始的时候,会将hasBeenStarted设置成true,在interrupt终止,但却没有将hasBeenStarted设置成false,因此在第二次调用start方法的时候,会抛出IllegalThreadStateException的错误。
public synchronized void start() { checkNotStarted(); hasBeenStarted = true; nativeCreate(this, stackSize, daemon); } private void checkNotStarted() { if (hasBeenStarted) { throw new IllegalThreadStateException("Thread already started"); } } |
解决方案
1、将extends Thread线程类改成implements Runnable,或者将Thread a = new Thread改为Runnable a = new Runnable;
2、每次new新的线程运行线程,new Thread(robot).start启动多次即可。
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。