多次实例化时 SwingWorker 线程/内存泄漏
我有一个显示预览内容的 JFrame,因为加载预览数据可能需要多次,我决定将加载操作放入 SwingWorker 中,这里是一个代码示例:
public void setPreviewContent(final String content) {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
frame.setCursor(java.awt.Cursor.getPredefinedCursor(
java.awt.Cursor.WAIT_CURSOR));
//DO My Work
return null;
}
@Override
protected void done() {
frame.setCursor(java.awt.Cursor.getPredefinedCursor(
java.awt.Cursor.DEFAULT_CURSOR));
}
};
worker.execute();
}
我的框架每次显示时都会初始化并每次处理关闭的时间:
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
初始化后,即显示调用 setPreviewContent()
方法并且它正常工作,唯一的问题是每次我关闭并重新打开预览框架时,都会有一个守护线程创建并留下running :
正如您很快就会看到的那样,大量线程仍处于运行状态,从而导致泄漏。 我该如何解决这个问题?
如果我使用标准线程,我就不会遇到这个问题......
I have a JFrame that shows a preview content, since the loading of preview data could take several times i decided to put the loading operation into a SwingWorker, here's a code sample :
public void setPreviewContent(final String content) {
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
frame.setCursor(java.awt.Cursor.getPredefinedCursor(
java.awt.Cursor.WAIT_CURSOR));
//DO My Work
return null;
}
@Override
protected void done() {
frame.setCursor(java.awt.Cursor.getPredefinedCursor(
java.awt.Cursor.DEFAULT_CURSOR));
}
};
worker.execute();
}
My frame it is initialized each time that is shown and is disposed each time that is closed with :
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
After the initialization and that is show the setPreviewContent()
method is called and it work properly, the only problem is that each time i close and reopen the preview frame a Daemon Thread is created and is left running :
As you can see soon a huge number of threads remain in running state, causing a leak.
How can i resolve the problem ?
If i use a standard Thread i don't have this problem ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JavaDoc 说:
您是否尝试关闭并重新打开它超过6次,看看最终是否没有添加新线程?我的猜测是您尚未达到线程池限制。
The JavaDoc says:
Did you try to close and reopen it more than 6 times, to see, whether eventually no new Thread is added? My guess is that you didn't reach the thread pool limit yet.