Thread Pool Test : Thread Pool « Threads « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. Email
14. Event
15. File Input Output
16. Game
17. Generics
18. Hibernate
19. I18N
20. J2EE
21. J2ME
22. JDK 6
23. JSP
24. JSTL
25. Language Basics
26. Network Protocol
27. PDF RTF
28. Reflection
29. Regular Expressions
30. Scripting
31. Security
32. Servlets
33. Spring
34. Swing Components
35. Swing JFC
36. SWT JFace Eclipse
37. Threads
38. Tiny Application
39. Velocity
40. Web Services SOA
41. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
C# / C Sharp
C# / CSharp Tutorial
ASP.Net
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Threads » Thread PoolScreenshots 
Thread Pool Test
Thread Pool Test

       /*
DEVELOPING GAME IN JAVA 

Caracteristiques

Editeur : NEW RIDERS 
Auteur : BRACKEEN 
Parution : 09 2003 
Pages : 972 
Isbn : 1-59273-005-1 
Reliure : Paperback 
Disponibilite : Disponible a la librairie 
*/
import java.util.LinkedList;

public class ThreadPoolTest {

  public static void main(String[] args) {
    if (args.length != 2) {
      System.out.println("Tests the ThreadPool task.");
      System.out
          .println("Usage: java ThreadPoolTest numTasks numThreads");
      System.out.println("  numTasks - integer: number of task to run.");
      System.out.println("  numThreads - integer: number of threads "
          "in the thread pool.");
      return;
    }
    int numTasks = Integer.parseInt(args[0]);
    int numThreads = Integer.parseInt(args[1]);

    // create the thread pool
    ThreadPool threadPool = new ThreadPool(numThreads);

    // run example tasks
    for (int i = 0; i < numTasks; i++) {
      threadPool.runTask(createTask(i));
    }

    // close the pool and wait for all tasks to finish.
    threadPool.join();
  }

  /**
   * Creates a simple Runnable that prints an ID, waits 500 milliseconds, then
   * prints the ID again.
   */
  private static Runnable createTask(final int taskID) {
    return new Runnable() {
      public void run() {
        System.out.println("Task " + taskID + ": start");

        // simulate a long-running task
        try {
          Thread.sleep(500);
        catch (InterruptedException ex) {
        }

        System.out.println("Task " + taskID + ": end");
      }
    };
  }

}
/**
 * A thread pool is a group of a limited number of threads that are used to
 * execute tasks.
 */

class ThreadPool extends ThreadGroup {

  private boolean isAlive;

  private LinkedList taskQueue;

  private int threadID;

  private static int threadPoolID;

  /**
   * Creates a new ThreadPool.
   
   @param numThreads
   *            The number of threads in the pool.
   */
  public ThreadPool(int numThreads) {
    super("ThreadPool-" (threadPoolID++));
    setDaemon(true);

    isAlive = true;

    taskQueue = new LinkedList();
    for (int i = 0; i < numThreads; i++) {
      new PooledThread().start();
    }
  }

  /**
   * Requests a new task to run. This method returns immediately, and the task
   * executes on the next available idle thread in this ThreadPool.
   * <p>
   * Tasks start execution in the order they are received.
   
   @param task
   *            The task to run. If null, no action is taken.
   @throws IllegalStateException
   *             if this ThreadPool is already closed.
   */
  public synchronized void runTask(Runnable task) {
    if (!isAlive) {
      throw new IllegalStateException();
    }
    if (task != null) {
      taskQueue.add(task);
      notify();
    }

  }

  protected synchronized Runnable getTask() throws InterruptedException {
    while (taskQueue.size() == 0) {
      if (!isAlive) {
        return null;
      }
      wait();
    }
    return (RunnabletaskQueue.removeFirst();
  }

  /**
   * Closes this ThreadPool and returns immediately. All threads are stopped,
   * and any waiting tasks are not executed. Once a ThreadPool is closed, no
   * more tasks can be run on this ThreadPool.
   */
  public synchronized void close() {
    if (isAlive) {
      isAlive = false;
      taskQueue.clear();
      interrupt();
    }
  }

  /**
   * Closes this ThreadPool and waits for all running threads to finish. Any
   * waiting tasks are executed.
   */
  public void join() {
    // notify all waiting threads that this ThreadPool is no
    // longer alive
    synchronized (this) {
      isAlive = false;
      notifyAll();
    }

    // wait for all threads to finish
    Thread[] threads = new Thread[activeCount()];
    int count = enumerate(threads);
    for (int i = 0; i < count; i++) {
      try {
        threads[i].join();
      catch (InterruptedException ex) {
      }
    }
  }

  /**
   * A PooledThread is a Thread in a ThreadPool group, designed to run tasks
   * (Runnables).
   */
  private class PooledThread extends Thread {

    public PooledThread() {
      super(ThreadPool.this, "PooledThread-" (threadID++));
    }

    public void run() {
      while (!isInterrupted()) {

        // get a task to run
        Runnable task = null;
        try {
          task = getTask();
        catch (InterruptedException ex) {
        }

        // if getTask() returned null or was interrupted,
        // close this thread by returning.
        if (task == null) {
          return;
        }

        // run the task, and eat any exceptions it throws
        try {
          task.run();
        catch (Throwable t) {
          uncaughtException(this, t);
        }
      }
    }
  }
}

           
       
Related examples in the same category
1. Defining a thread for a thread poolDefining a thread for a thread pool
2. Thread pool demo
3. Thread Pools 1
4. Thread Pools 2Thread Pools 2
5. Thread pool
6. Thread Pool 2Thread Pool 2
w__w__w_.___j__a_v_a_2s__._c__o___m | Contact Us
Copyright 2003 - 08 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.