(Java 7 NIO.2)监视服务线程的自定义名称

Ant*_*LLE 6 java nio java-7

在Java 7中使用nio.2,当您创建这样的监视服务时:

WatchService watcher = FileSystems.getDefault().newWatchService();
Run Code Online (Sandbox Code Playgroud)

然后,启动后台线程,在无限循环内轮询文件系统事件.此线程的名称是"Thread-n",在调查线程转储或分析会话期间这有点令人讨厌.

我们可以更改该线程的名称吗?

ass*_*ias 2

从实现来看,直接看似乎不太可能。如果您不介意稍微修改一下,您可以找到该线程并重命名它。

类似于(//TODO:进行错误检查):

Set<Thread> threadsBefore = Thread.getAllStackTraces().keySet();
WatchService ws = FileSystems.getDefault().newWatchService();

//I don't need to wait here on my machine but YMMV

Set<Thread> threadsAfter = Thread.getAllStackTraces().keySet();
threadsAfter.removeAll(threadsBefore);
Thread wsThread = threadsAfter.toArray(new Thread[1])[0];

System.out.println("wsThread = " + wsThread);

wsThread.setName("WatchService Thread");

Set<Thread> justChecking = Thread.getAllStackTraces().keySet();
System.out.println("justChecking = " + justChecking);
Run Code Online (Sandbox Code Playgroud)