我运行代码时遇到此异常。即使代码运行正常,我在终端上也会遇到一些例外
Exception in thread "AWT-EventQueue-1" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
at SR.start(SR.java:38)
at SR.mouseClicked(SR.java:212)
at java.awt.Component.processMouseEvent(Component.java:6536)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Window.processEvent(Window.java:2025)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at org.GNOME.Accessibility.AtkWrapper$5.dispatchEvent(AtkWrapper.java:700)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
我做错了什么?
我的start()
方法
private void start() throws IllegalStateException {
if (HelperThread == null)
HelperThread = new Thread(this);
HelperThread.start();
}
答案 0 :(得分:1)
您似乎开始使用相同的Thread
两次,这是不允许的。
如果您希望重复使用同一个帖子,我建议您改为创建ExecutorService
。
答案 1 :(得分:0)
问题是如果HelperThread不为null(它已经存在)并且你调用HelperThread.start()则尝试启动()一个已经启动或完成它处理的线程。如果要重新启动处理,则必须先停止该线程。要优雅地执行此操作,请在实际线程中使用while(running){}模式。然后,在start() - 方法中,将标志设置为false,等待线程死亡,然后启动一个新线程:
private void start() throws IllegalStateException {
if (HelperThread != null) {
running = false;
HelperThread.join(); // wait for it to die...
}
// Start fresh...
HelperThread = new Thread(this);
HelperThread.start();
}
另外,作为旁注,请避免使用大写字母作为变量的第一个字母。它应该是“helperThread”。