Coordinates threads for multi-threaded operations : Lock Synchronize « 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. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
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
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Threads » Lock SynchronizeScreenshots 
Coordinates threads for multi-threaded operations
  
/* Copyright (C) 2005-2008 by Peter Eastman

   This program is free software; you can redistribute it and/or modify it under the
   terms of the GNU General Public License as published by the Free Software
   Foundation; either version 2 of the License, or (at your option) any later version.

   This program is distributed in the hope that it will be useful, but WITHOUT ANY 
   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */


import java.util.concurrent.atomic.*;
import java.util.*;

/**
 * This class coordinates threads for multi-threaded operations.  The execution model
 * provided by this class is a single "task" (e.g. tracing a ray through a single pixel)
 * which must be executed many times.  The task is parameterized by a single index
 * (e.g. the column containing the pixel).
 * <p>
 * To use this class, pass it an object which implements the Task interface.  It
 * automatically creates an appropriate number of threads based on the number of
 * available processors.  When you call run(), the task is repeatedly executed by
 * the worker threads, with the index running
 * over the desired range.  You may invoke run() any number of times (e.g. once
 * for each row of the image).  Finally, call finish() to clean up the worker threads.
 */

public class ThreadManager
{
  private int numIndices;
  private AtomicInteger nextIndex;
  private Thread thread[];
  private HashSet<Thread> waitingThreads;
  private Task task;
  private Object controller;
  private boolean controllerWaiting;

  /**
   * Create a new uninitialized ThreadManager.  You must invoke setNumIndices() and setTask()
   * to initialize it before calling run().
   */

  public ThreadManager()
  {
    this(0null);
  }

  /**
   * Create a new ThreadManager.
   *
   @param numIndices      the number of values the index should take on (from 0 to numIndices-1)
   @param task            the task to perform
   */

  public ThreadManager(int numIndices, Task task)
  {
    this.numIndices = numIndices;
    this.task = task;
    nextIndex = new AtomicInteger(numIndices);
    controller = new Object();
    controllerWaiting = false;
    waitingThreads = new HashSet<Thread>();
  }

  /**
   * Create and start the worker threads.  This is invoked the first time run() is called.
   */

  private void createThreads()
  {
    // Create a worker thread for each processor.

    thread = new Thread [Runtime.getRuntime().availableProcessors()];
    for (int i = 0; i < thread.length; i++)
    {
      thread[inew Thread("Worker thread "+(i+1)) {
        public void run()
        {
          // Repeatedly perform the task until we are finished.

          while (true)
          {
            try
            {
              int index = nextIndex();
              task.execute(index);
            }
            catch (InterruptedException ex)
            {
              task.cleanup();
              return;
            }
            catch (Exception ex)
            {
              cancel();
              ex.printStackTrace();
            }
          }
        }
      };
      thread[i].start();
    }
  }

  /**
   * Set the number of values the index should take on.  This must be invoked from the same
   * thread that instantiated the ThreadManager and that calls run().
   */

  public void setNumIndices(int numIndices)
  {
    this.numIndices = numIndices;
    nextIndex.set(numIndices);
  }

  /**
   * Set the Task to be executed by the worker threads.  If another Task has already been set,
   * that one is discarded immediately and cleanup() will never be invoked on in.  This method
   * must be invoked from the same thread that instantiated the ThreadManager and that calls run().
   */

  public void setTask(Task task)
  {
    this.task = task;
  }

  /**
   * Perform the task the specified number of times.  This method blocks until all
   * occurrences of the task are completed.  If the current thread is interrupted
   * while this method is in progress, all of the worker threads will be interrupted
   * and disposed of.
   */

  public void run()
  {
    controllerWaiting = false;
    nextIndex.set(0);
    waitingThreads.clear();
    if (thread == null)
      createThreads();

    // Notify all the worker threads, then wait for them to finish.

    synchronized (this)
    {
      notifyAll();
    }
    synchronized (controller)
    {
      try
      {
        controllerWaiting = true;
        controller.wait();
      }
      catch (InterruptedException ex)
      {
        finish();
      }
    }
  }

  /**
   * Cancel a run which is in progress.  Calling this method does not interrupt any tasks that
   * are currently executing, but it prevents any more from being started until the next time
   * run() is called.
   */

  public void cancel()
  {
    nextIndex.set(numIndices);
  }

  /**
   * Dispose of all the worker threads.  Once this has been called, do not call run() again.
   */

  public void finish()
  {
    if (thread != null)
      for (int i = 0; i < thread.length; i++)
        thread[i].interrupt();
  }

  private int nextIndex() throws InterruptedException
  {
    int index;
    while ((index = nextIndex.getAndIncrement()) >= numIndices)
    {
      // Wait until run() is called again.

      synchronized (this)
      {
        waitingThreads.add(Thread.currentThread());
        if (waitingThreads.size() == thread.length)
        {
          while (!controllerWaiting)
            wait(1);
          synchronized (controller)
          {
            controller.notify();
          }
        }
        wait();
      }
    }
    return index;
  }

  /**
   * This interface defines a task to be performed by the worker threads.
   */

  public static interface Task
  {
    /**
     * Execute the task for the specified index.
     */

    public void execute(int index);

    /**
     * This is called once from each worker thread when finish() is called.  It gives a chance
     * to do any necessary cleanup.
     */

    public void cleanup();
  }
}

   
    
  
Related examples in the same category
1. Thread: Dining Philosophers
2. Synchronizing on another objectSynchronizing on another object
3. Operations that may seem safe are not, when threads are presentOperations that may seem safe are not, when threads are present
4. Synchronizing blocks instead of entire methodsSynchronizing blocks instead of entire methods
5. Boolean lockBoolean lock
6. Static synchronized blockStatic synchronized block
7. Thread notifyThread notify
8. Thread deadlockThread deadlock
9. Synchronize methodSynchronize method
10. Threads joinThreads join
11. Static synchronizeStatic synchronize
12. No synchronizeNo synchronize
13. Thread synchronizationThread synchronization
14. Synchronized Block demoSynchronized Block demo
15. Interruptible Synchronized Block Interruptible Synchronized Block
16. SignalingSignaling
17. Simple Object FIFOSimple Object FIFO
18. Object FIFOObject FIFO
19. Byte FIFOByte FIFO
20. Thread Synch
21. Daemon Lock
22. Determining If the Current Thread Is Holding a Synchronized Lock
23. Handle concurrent read/write: use synchronized to lock the data
24. Lock for read and write
25. Read Write Lock
26. A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong.
27. Invoke a series of runnables as closely to synchronously as possible
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.