Tuesday May 13, 2008 Controlling Threads with concurrent package
| For long, I have been using Runnable interface to get the long running non interactive natured stuff done in the background. In some previous posts, I had mentioned the crude way of using ThreadGroup to achieve pooling sort of control. It was also fun working on a task scheduler that ran tasks in controlled set of threads. Logically, what do you need ? The pool size, the Runnable targets, an infinite loop and a data structure to control the thread scheduling !! So the code looked really.. as we call in India.. 'Fundooo' ! But when I look at the Concurrent package, the same code looks like a floppy disk in front of a DVD. I haven't explored the package completely so don't want to say a blue ray disk. |
import java.util.concurrent.*;
import java.util.Random;
public class TestConcurrent {
public static void main(String args[]) {
ExecutorService runner = Executors.newSingleThreadExecutor();
ExecutorService pool = Executors.newFixedThreadPool(5);
int style = 1;
try { style = (new Integer(args[0])).intValue();
} catch (Exception e ) {}
switch(style) {
case 1:
System.out.println("Running in separate threads...");
for(int oldstyle=0; oldstyle<10; oldstyle++) {
new Thread(new TestRunnable()).start();
}
break;
case 2:
System.out.println("Running in a worker thread....");
for(int newstyle=0; newstyle<10; newstyle++) {
runner.submit(new TestRunnable());
}
runner.shutdown();
break;
case 3:
System.out.println("Running in a thread pool....");
for(int newstyle=0; newstyle<10; newstyle++) {
pool.submit(new TestRunnable());
}
pool.shutdown();
break;
}
System.out.println("Main is over....");
}
}
class TestRunnable implements Runnable {
private static int i = 0;
private int member = 0;
private int runtime = 0;
public TestRunnable() {
member = ++i;
runtime = (new Random()).nextInt(10);
}
public void run() {
System.out.println("I am instance " + member + " with runtime " + runtime + " seconds");
try { Thread.sleep(runtime * 1000); }catch(Exception e) {System.out.println("Interrupted");}
System.out.println("Instance "+ member + " runtime over...!");
}
}
