How to make a Single Thread Pool via Java using JDK classes
The idea is to construct a queue of tasks, in terms of Threads, to get executed one after the other. The JDK itself has classes to do Thread Pools: java.util.concurrent.ExecutorService.
This is just one way of using it.
Try the following code,
Thread Pool Class
package gunith.evillab;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SingleThreadPool {
public static void main(String[] args) {
ExecutorService xServ = Executors.newSingleThreadExecutor();
for(int i=0;i<4;i++){
xServ.submit(new Boogie(i));
}
xServ.shutdown();
System.out.println("Sent all the Boogie's to dance");
}
}
The (Dummy) Runnable Class
class Boogie implements Runnable{
int id;
public Boogie(int id) {
this.id = id;
}
@Override
public void run() {
for (int i=0;i<3;i++) {
System.out.println(id + " does the boogie times x " + i);
try {
Thread.sleep(3*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Categories:
Java
Written on November 21, 2010