java - How to determine if a thread is main thread in Java?
问题描述
In Java, programmers can change the name of main thread. So how to determine if a thread is main thread?
package bj.thread;
public class ThreadApp2 {
public static void main(String[] args) {
System.out.printf("The main thread name is %s\n", Thread.currentThread().getName());
Thread.currentThread().setName("not-main");
System.out.printf("The main thread name is %s\n", Thread.currentThread().getName());
}
}
The output:
The main thread name is main
The main thread name is not-main
解决方案
public static boolean isMainThread(){
return Thread.currentThread().getId() == 1;
}
免责声明:文档中没有说明 id == 1 => 它是主线程
推荐阅读
- node.js - 谷歌助理会话实体有时工作有时不工作.. nodejs
- php - 如何根据 PHP/Laravel 中的值打印或存储具有选定属性的 html 选择标签?
- python - 使用 xlsxwriter 居中对齐(无条件格式)
- sql - 这个访问查询有什么问题?
- hybris - Smartedit 中的重叠组件
- ios - 如何像谷歌日历一样将单元格的内容滚动到表格视图中的另一个单元格中?
- asp.net - ASP.NET httphandlers webconfig 文件集成模式
- node.js - 如何在快速服务器中进行 API 调用
- react-native - react-nativ-camera -- 访问 java 文件功能
- java - 以编程方式将变量标头添加到使用 RollingRandomAccessFileAppender 创建的翻转日志