在Java中如何检查哪个线程正在执行代码?

发布于 2024-10-12 01:45:16 字数 159 浏览 4 评论 0原文

我有一个多线程 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

故乡的云 2024-10-19 01:45:16

Thread.currentThread().getName()

Thread.currentThread().getName()

前事休说 2024-10-19 01:45:16

除了adamfisk的出色建议之外,还有一个方便的方法专门测试当前线程是否是EDT线程:

EventQueue.isDispatchThread()

In addition to adamfisk's excellent suggestion, there is also a convenience method for specifically testing whether the current thread is the EDT thread:

EventQueue.isDispatchThread()
戒ㄋ 2024-10-19 01:45:16

您可以尝试

assert Thread.currentThread() == expectedThread;

使用该名称的问题是任意数量的线程都可以使用该名称,例如,如果您特别偏执,您可能会担心这样的代码。

Thread.t = Thread.currentThread();
String name = t.getName();
t.setName("UI thread");
callUIThreadOnlyMethod();
t.setName(name);

You can try

assert Thread.currentThread() == expectedThread;

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.

Thread.t = Thread.currentThread();
String name = t.getName();
t.setName("UI thread");
callUIThreadOnlyMethod();
t.setName(name);
风筝有风,海豚有海 2024-10-19 01:45:16

考虑颠倒问题。考虑预防而不是强制。

如果类 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.

最近可好 2024-10-19 01:45:16

我会在 A 类的代码中这样做:

if(!"UI thread".equals(Thread.currentThread().getName())){
    throw new IllegalStateException("wrong thread running this class, thread name:"+Thread.currentThread().getName());
}

I would do like this in my code in class A:

if(!"UI thread".equals(Thread.currentThread().getName())){
    throw new IllegalStateException("wrong thread running this class, thread name:"+Thread.currentThread().getName());
}
深海蓝天 2024-10-19 01:45:16

您还可以使用日志记录(例如 log4j 或 logback)检查线程名称,只需设置一个包含 %thread 的模式,如下所示:

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <root level="INFO">
     <appender-ref ref="STDOUT" />
  </root>
</configuration>

You can also check thread name using logging e.g. log4j or logback, just set a pattern including %thread like this:

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>
  <root level="INFO">
     <appender-ref ref="STDOUT" />
  </root>
</configuration>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文