How to let a Thread wait
You need a Object that the Threads shouldnt use parallel in this case aObj.
its indifferent which class aObj is. The first Thread will wait at the aObj.wait() line until another Thread calls aObj.notify().
The run Method in the first Thread:
synchronized(aObj) {
try {
//Doing something
//Wait at the next line
aObj.wait();
//Not reached until aObj.notify is called
} catch (InterruptedException e) {
e.printStackTrace();
}
}
The second Thread
synchronized(aObj) {
aObj.notify();
}
How to Listen to a File change
First you need a WatcherService and a Path to the Directory in which you want to Listen for file changes. Then you have to register on which Events you want to listen very important is that you add the static import.
- ENTRY_CREATE - A directory entry is created
- ENTRY_DELETE – A directory entry is deleted.
- ENTRY_MODIFY – A directory entry is modified.
- OVERFLOW – Indicates that events might have been lost or discarded. You do not have to register for the OVERFLOW event to receive it.
For more information look at this site: Watching a Directory for Changes
import static java.nio.file.StandardWatchEventKinds.*;
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("C:\\PATHTOYOUR\\DIRECTORY\\");
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
After that you should create a while(true) loop and wait for a event. Take the event with watcher.take() and get a List of the events by calling key.pollEvents(). Iterate through it and you can get the filename and the Event.
while(true){
WatchKey key = watcher.take();
//Wait until a events arrives
List<WatchEvent<?>> events = key.pollEvents();
for(int i = 0; i < events.size(); i++){
//Get the kind of Event
WatchEvent.Kind<?> kind = events.get(i).kind();
//Get the filename
WatchEvent<Path> ev = (WatchEvent<Path>) events.get(i);
Path filename = ev.context();
//Differentiate between the different events
if(kind == ENTRY_CREATE){
}else if(kind == ENTRY_DELETE){
}else if(kind == ENTRY_MODIFY){
}else if(kind == OVERFLOW){
}
//Exit the loop if the key is inaccessible
boolean valid = key.reset();
if (!valid) {
break;
}
}
}
Take this two Code Snippets and put them into a Thread and you have your own Thread which is called on a File Event.