You are on page 1of 3

import java.util.

LinkedList; class ThreadTaskWorker extends Thread { private ThreadPool pool; private ThreadTaskWorker worker = null; public ThreadTask(ThreadPool thePool) { pool = thePool; } public void run() { while (true) { // blocks until job Runnable job = pool.getNext(); try { job.run(); } catch (Exception e) { // Ignore exceptions thrown from jobs System.err.println("Job exception: " + e); } } } } public class ThreadPool { private LinkedList tasks = new LinkedList(); public ThreadPool(int size) { for (int i = 0; i < size; i++) { Thread thread = new ThreadTaskWorker(this); thread.start(); } } public void delegateTask (Runnable task) { synchronized (tasks) { tasks.addLast(task); tasks.notify(); } }

public Runnable getNext() { Runnable returnVal = null; synchronized (tasks) { while (tasks.isEmpty()) { try { tasks.wait(); } catch (InterruptedException ex) { System.err.println("Interrupted"); } } returnVal = (Runnable) tasks.removeFirst(); } return returnVal; }

public class BusinessApplMain { public static void main (String args[]) { { ThreadPool pool = new ThreadPool(10); while (true) { //getTask() - reading from DB or flat file //creates a Request bean object of the task if ( reqObject != null ) { Runnable task = new Task(reqObject); pool.delegateTask(runner); reqObject = null; } } } }

public class Task implements Runnable { private Request obj = null;

public Task (Request obj) { this.obj = obj; } public void run () { // do somethhing with the task request obj } }

You might also like