Today I stummbled upon something I had not done, this may be old hat for some of you, but none the less I thought it was pretty cool and thought I would share. I was working on a class that needed to kick off a thread, so i started down the path I knew and created a class that implemented Runnable, created the run method, and it looked something like the following:
public class MyThread implements Runnable {
private Boolean running;
public MyThread(Boolean running) {
this.running = running;
}
public void run() {
while (running) {
process();
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
public void process() {
//Do someting cool here
}
public void setRunning(Boolean running) {
this.running = running;
}
}
public class ExecuteThread {
private Boolean running = true;
private MyThread myThread;
public void activate() {
myThread = new MyThread(running);
Thread thread = new Thread(myThread);
thread.start();
}
public void deactivate() {
myThread.setRunning(false);
}
}
Using the ScheduledExecutorService provided in the java.util.concurrent package you can handle the execution of a thread and control the initial delay, delay, and the unit of time with one method call. Something like the following:
public class MyThread implements Runnable {
public MyThread() {
}
public void run() {
process();
}
public void process() {
//Do something cool here
}
}
public class ExecuteThread {
private MyThread myThread;
private final ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
public void activate() {
myThread = new MyThread();
scheduler.scheduleWithFixedDelay
(myThread, 0, 10, TimeUnit.SECONDS);
}
public void deactivate() {
scheduler.shutdown();
}
}
Again, this might be old news for some of you, but I thought this was a very effective way to handle threading and it really cleaned up my code in the end.
Showing posts with label Threading. Show all posts
Showing posts with label Threading. Show all posts
Friday, May 18, 2007
Java Threading - ScheduledExecutorService
Posted by
Chad Gallemore
at
3:22:00 PM
7
comments
Subscribe to:
Posts (Atom)
