发布于 2021-02-13 12:00:11
如果您关心有多少线程在监视使用,可以很容易地编写一个小程序来检查:
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
public class Example {
public static void main(String... args) throws IOException, InterruptedException {
final WatchService watcher = FileSystems.getDefault().newWatchService();
final int number_of_watches = 100;
final Path[] paths = new Path[number_of_watches];
final WatchKey[] watchKeys = new WatchKey[number_of_watches];
final Path tmp = Files.createTempDirectory("watch");
for (int i = 0; i < number_of_watches; i++) {
paths[i] = tmp.resolve("dir" + i);
Files.createDirectory(paths[i]);
watchKeys[i] = paths[i].register(watcher,
ENTRY_CREATE,
ENTRY_DELETE,
ENTRY_MODIFY);
System.out.println(paths[i]);
}
Thread.getAllStackTraces().keySet().stream().forEach(t -> System.out.println(t));
for (;;) {
WatchKey key = watcher.take();
System.out.println("Change in " + key.watchable());
}
}
}线程名部分的输出是:
Thread[Common-Cleaner,8,InnocuousThreadGroup]
Thread[main,5,main]
Thread[Finalizer,8,system]
Thread[FileSystemWatcher,5,main]
Thread[Signal Dispatcher,9,system]
Thread[Reference Handler,10,system]
Thread[Notification Thread,9,system]所以这只使用了一个线程,即Thread[FileSystemWatcher,5,main]
https://stackoverflow.com/questions/66181513
复制相似问题