集册 Java实例教程 使用线程事件处理程序监视

使用线程事件处理程序监视

欢马劈雪     最近更新时间:2020-01-02 10:19:05

478
观看线程事件处理程序

import java.io.IOException;

import java.nio.file.FileSystems;/* 来自 时 代 J a v a 公 众 号 - N o w J a v  a . c o m*/

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardWatchEventKinds;

import java.nio.file.WatchEvent;

import java.nio.file.WatchEvent.Kind;

import java.nio.file.WatchKey;

import java.nio.file.WatchService;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;/**n o w j a v a . c o m - 时  代  Java**/

import java.util.concurrent.TimeUnit;


class Print implements Runnable {

  private Path doc;

  Print(Path doc) {

    this.doc = doc;

  }

  @Override

  public void run() {

    try {

      Thread.sleep(200);

      System.out.println("Printing: " + doc);

    } catch (InterruptedException ex) {

      System.err.println(ex);

    }

  }

}

public class Main {

  public static void main(String[] args)  throws IOException, InterruptedException{

    final Path path = Paths.get("C:/test");

    Map<Thread, Path> threads = new HashMap<>();    

    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {

      path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,

          StandardWatchEventKinds.ENTRY_DELETE);

      while (true) {

        final WatchKey key = watchService.poll(10, TimeUnit.SECONDS);

        if (key != null) {

          for (WatchEvent<?> watchEvent : key.pollEvents()) {

            final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;

            final Path filename = watchEventPath.context();

            final Kind<?> kind = watchEvent.kind();

            if (kind == StandardWatchEventKinds.OVERFLOW) {

              continue;

            }

            if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

              System.out

                  .println("Sending the document to print -> " + filename);

              Runnable task = new Print(path.resolve(filename));

              Thread worker = new Thread(task);

              worker.setName(path.resolve(filename).toString());

              threads.put(worker, path.resolve(filename));

              worker.start();

            }


            if (kind == StandardWatchEventKinds.ENTRY_DELETE) {

              System.out.println(filename + " was successfully printed!");

            }

          }

          boolean valid = key.reset();

          
展开阅读全文