如何命名 SwingWorker 线程?开放代码或最佳实践
我正在尝试调试 SwingWorker 线程中发生的可怕异常。如果我可以命名我的 SwingWorker 线程,那么我可以更好地解释我收到的堆栈跟踪。
似乎不可能命名 SwingWorker 线程(是吗?)。我正在寻找任何最佳实践或“技巧”来帮助我正确识别我的工作线程,而不仅仅是在我的代码中添加日志语句。
I'm trying to debug a horrible exception that is occurring in a SwingWorker thread. If I could name my SwingWorker threads, then I could better interpret the stack traces I am receiving.
It doesn't seem possible to name a SwingWorker thread (is it?). I'm looking for any best practices or 'tricks' to help me properly identify my worker threads, short of just peppering my code w/ log statements.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然您无权访问 SwingWorker 正在使用的 ThreadFactory,但您可以在 SwingWorker 正在运行的任何类的 run() 或 call() 方法中调用 Thread.currentThread().setName() 。
只需确保在线程实际执行代码时设置该值即可
While you don't have access to the ThreadFactory that SwingWorker is using, you can call Thread.currentThread().setName() in your run() or call() method of whatever class the SwingWorker is running.
Just be sure that you're setting that value when the thread is actually executing the code
SwingWorker 使用的线程来自 Executors.defaultThreadFactory,这意味着它来自池。因此,如果“MyXYZThread”被系统中另一个无法重命名线程的 SwingWorker 重用,则命名线程可能会产生误导。
我将扩展 SwingWorker 以包含名称并在引发异常时记录该名称。
注意:我不想让调用者负责处理异常,但我没有找到一种方法可以在不改变 SwingWorker 合同的情况下做到这一点。
用法:
The Thread used by SwingWorker is from an Executors.defaultThreadFactory which means it's from a pool. So, naming the thread could be misleading if "MyXYZThread" gets reused for another SwingWorker in the system that fails to rename the thread.
I'd extend the SwingWorker to include a name and log that name when throwing an exception.
Note: I'd rather not make the caller responsible for handling the exception, but I don't see a way to do it without altering the contract of SwingWorker.
Usage:
您应该能够使用反射来获取线程并调用 setName。您需要使用 setAccessible 方法来执行此操作,并进行一些挖掘以查找需要访问的变量的名称。
我不喜欢这种方法,但它可能和其他方法一样“hacky”......
You should be able to use reflection to get the thread and call setName as well. You would need to make use of the setAccessible method to do that and some digging around to find the names of the variables you need to access.
I would not prefer this method, but it may be just as "hacky" as any other way...
最佳实践是使用已经提到的 Thread.currentThread().setName(String)。
一个“技巧”是为 SwingWorkers 设置 ThreadFactory:
它使用 sun.awt 包中的一个类,因此您已收到警告。
The best practice would be to use the already mentioned Thread.currentThread().setName(String).
A "trick" would be setting the ThreadFactory for SwingWorkers:
This uses a class from the sun.awt package, so you've been warned.
导入 javax.swing.SwingWorker;
注意: 在 NetBeans 中,直到我暂停应用程序或命中断点后,swingworker 线程的新名称才会出现在调试器中。
import javax.swing.SwingWorker;
NOTE: In NetBeans, the new name of the swingworker thread did not appear in the debugger until I paused the application or hit a breakpoint.