在Java中如何检查哪个线程正在执行代码?
我有一个多线程 Java 程序,其中包含一系列有关线程的规则:例如,类 A 中的代码只能从 UI 线程调用; B 类中的 3 个方法必须仅从网络线程等中调用。
关于如何进行断言或其他代码检查以确保遵循这些规则,有什么建议吗?我想做相当于测试“不变量”的操作,以防止线程使用时出现编码错误。
I have a multi-threaded Java program with a bunch of rules around threading: For example, code in class A should only be called from the UI thread; 3 methods in class B must be called only from the network thread, etc.
Any suggestions on how to do assertions or other code checks that these rules are being followed? I'd like to do the equivalent of testing for "invariants" to prevent coding errors on thread usage.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Thread.currentThread().getName()
Thread.currentThread().getName()
除了adamfisk的出色建议之外,还有一个方便的方法专门测试当前线程是否是EDT线程:
In addition to adamfisk's excellent suggestion, there is also a convenience method for specifically testing whether the current thread is the EDT thread:
您可以尝试
使用该名称的问题是任意数量的线程都可以使用该名称,例如,如果您特别偏执,您可能会担心这样的代码。
You can try
The problem with using the name is that any number of threads can use that name e.g. if you are particularly paranoid you might worry about code like this.
考虑颠倒问题。考虑预防而不是强制。
如果类 Mangalor 只能在 UI 线程中运行,请限制 Mangalor 类对 UI 类的可见性。
如果 CanOnString 类的方法 talk() 和 Listen() 必须仅在网络线程中运行,请限制这些方法对在网络线程中运行的类的可见性。
Consider inverting the question. Consider prevention instead of enforcement.
If class Mangalor can only be run in a UI thread, limit the visibility of the Mangalor class to UI classes.
If methods talk() and listen() of class CanOnString must only be run in a networking thread, limit the visibility of those methods to classes that you run in your networking thread.
我会在 A 类的代码中这样做:
I would do like this in my code in class A:
您还可以使用日志记录(例如 log4j 或 logback)检查线程名称,只需设置一个包含
%thread
的模式,如下所示:You can also check thread name using logging e.g. log4j or logback, just set a pattern including
%thread
like this: