我有修改文件时执行的代码
public class WatchQueueReaderTask<Void> extends Task {
...
protected Object call() throws Exception {
try {
// get the first event before looping
WatchKey key = myWatcher.take();
while (key != null) {
// we have a polled event, now we traverse it and
// receive all the states from it
for (WatchEvent event : key.pollEvents()) {
WatchEvent.Kind eventType = event.kind();
if (eventType == OVERFLOW) {
continue;
}
process(event);
if (isCancelled()) {
System.out.println("WatchQueueReaderTask::call isCancelled");
return null;
}
}
key.reset();
key = myWatcher.take();
}
} catch (InterruptedException e) {
ArrayList<WatchFileItem> auxList = threadFileToWatch;
for (WatchFileItem obj : auxList) {
if (obj.file != null) {
try {
obj.file.close();
} catch (IOException ex) {
System.out.println("errore in file close");
Logger.getLogger(WatchQueueReaderTask.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
//e.printStackTrace();
}
System.out.println("Stopping thread");
return null;
}
...
private synchronized void process(WatchEvent evt) {
... }
}
我用它来打电话:
ThreadFactory processingThreadFactoryForRealtime = null;
ExecutorService processingThreadFactoryForRealtimeExecutor = null;
WatchQueueReaderTask mywatchQueueReader = null;
processingThreadFactoryForRealtime = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName("FileWatcherTask");
t.setDaemon(true);
return t;
}
};
processingThreadFactoryForRealtimeExecutor = Executors.newSingleThreadExecutor(processingThreadFactoryForRealtime);
mywatchQueueReader = new WatchQueueReaderTask(realtimePath, watcherServiceForRealtime, fileToWatchForRealtime);
processingThreadFactoryForRealtimeExecutor.execute(mywatchQueueReader);
问题是同时执行多个方法process()而不等待前一个完成。
我哪里错了?