Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.File;
import java.util.logging.Logger;
public class ThreadedDemo {
private static Logger logger = Logger.getLogger("demo");
// "Inner class" represents a single thread that runs forever, looking for
// a certain file to appear, then "processes it," for demo
// purposes just renaming it to another name
static class Worker implements Runnable {
private File file;
private long delay;
public Worker(String sourceFile, long delay) {
this.file = new File(sourceFile);
this.delay = delay;
}
// returns the name of the current thread.
// other logging APIs support thread name out of the box,
// doesn't seem like java util logging does that.
private String threadName() {
return Thread.currentThread().getName();
}
// this will move file to another name
private void processFile() {
long timestamp = System.currentTimeMillis();
File newFile = new File(file.getAbsolutePath() + "." + timestamp);
logger.info(threadName() + ": moving " + file + " to " + newFile);
if (!file.renameTo(newFile)) {
throw new RuntimeException("cannot move file " + file + " to " + newFile);
}
}
// thread sleeps for specified delay ms.
private void sleep() {
logger.fine(threadName() + ": sleeping " + delay + " ms.");
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
logger.severe(threadName() + ": interrupted, this should really never happen");
}
}
// this method is the entry point to the thread. will loop forever,
// waking up and checking for the file
public void run() {
logger.info(threadName() + ": watching for file " + file);
while(true) {
if (file.exists()) {
processFile();
}
sleep();
}
}
}
public static void main(String[] args) {
ThreadGroup td = new ThreadGroup("worker threads");
// keep the running while all threads in this group are alive
td.setDaemon(true);
// start 5 threads
for (int i = 1; i <= 5; i++) {
// each thread gets its own name, logging can be configured in
// such a way that thread name comes out in each log message
new Thread(td, new Worker("input_" + i + ".txt", 1000), "Worker_" + i).start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.