如何管理默认的Java SwingWorker线程池?
我有一个使用 2 个长时间运行的 SwingWorker 任务的应用程序,并且我刚刚遇到了几台具有更新的 JVM 的 Windows 计算机,它们仅启动其中一个任务。没有指示任何错误,因此我必须假设默认线程池只有一个线程,因此当我尝试执行第二个 SwingWorker 对象时,它正在排队。
那么,(1) 如何检查默认 SwingWorker 线程池中有多少线程可用,以及 (2) 如果需要更多线程,如何添加线程?
还有什么我应该知道的吗?这种明显的单线程线程池情况违背了我的所有期望。
我正在设置一个 ThreadPoolExecutor 但这似乎很错误......
I've got an application that uses 2 long-running SwingWorker tasks and I've just encountered a couple of Windows computers with updated JVMs that only start one of the them. There are no errors indicated so I have to assume that the default thread pool has only a single thread and therefore the second SwingWorker object is getting queued when I try to execute it.
So, (1) how do I check check how many threads are available in the default SwingWorker thread pool, and (2) how do I add threads if I'm going to need more?
Anything else that I should know? This apparent single-thread thread-pool situation goes against all of my expectations.
I'm setting up a ThreadPoolExecutor but this seems so wrong...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
默认的 SwingWorker 线程池实际上有 10 个线程(在私有变量 SwingWorker.MAX_WORKER_THREADS 中定义)。如果您只看到其中一个任务启动,我会使用 JConsole 或其他类似工具检查另一个线程的状态。
没有简单的方法可以搞乱默认的 SwingWorker 线程池(它是私有的,不会被任何公共方法公开)。如果默认池不起作用,则将 SwingWorkers 添加到您自己的线程池是处理该问题的预期方法。
The default SwingWorker thread pool actually has 10 threads (defined in the private variable SwingWorker.MAX_WORKER_THREADS). If you're only seeing one of your tasks start, I'd check the state of the other thread with JConsole or some other similar tool.
There's no easy way to mess with the default SwingWorker thread pool (it's private and not exposed by any of the public methods). Adding SwingWorkers to your own thread pool is the expected way to handle it if the default pool doesn't work.
也许有点晚了,但是,较新的 Java 版本中存在一个错误:
由于 swingworker 池中的一个线程而导致 SwingWorker 死锁
Maybe a bit late but, there's a bug in the newer Java versions:
SwingWorker deadlocks due one thread in the swingworker-pool
在JDK 6下,默认的工作线程数为10。
通常不需要创建ThreadPoolExecutor,swingworker使用的默认线程池通常就足够了。创建 ThreadPoolExecutor 可能很危险,因为某些静态方法仅创建具有单个线程的池。
您可能需要向这些线程添加日志记录(如果尚未存在)并检查日志。可能是其他一些同步问题导致您的第二个后台任务停止。
Under JDK 6, the default number of worker threads is 10.
You don't normally need to create a ThreadPoolExecutor, the default thread pool used by swing worker is usually sufficient. Creating a ThreadPoolExecutor can be dangrous, as some of the static methods only create a pool with a single thread.
You may want to add logging to these threads, if not already present, and inspect the logs. It may be some other synchronization problem is stopping your second background task.