skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, September 19, 2012

Thread Manager

Posted by Admin at 12:49 AM – 0 comments
 
ThreadManager is a generalized class to work with java threads of specified count in a controlled manner

Features
- Contains synchronized methods
- The Maximum number of threads in a pool can be specified
- contains static variables so that threads are initiated based on a specific count


public class ThreadManager {

    private static java.util.Vector threadPool = null;
    private int MAX_THREADS = 5;
    private static ThreadManager threadManager = null;
    
 
    private ThreadManager() {
     threadPool = new java.util.Vector();
   
    }
    
    public synchronized static ThreadManager getInstance() {
        if (threadManager == null) {
          threadManager = new ThreadManager();
        }
        return threadManager;
    }
    
    public synchronized  Object getThreadInstance() {
        Object ob = null;
        if (threadPool != null) {            
            if (threadPool.size() < MAX_THREADS) {
                ob = new Object();
                threadPool.add(ob);         
                System.out.println("New thread has been added into the pool");
            }           
        }
        return ob;
    }
    
    public synchronized void removeThread(Object ob) {
        if (ob != null) { 
         threadPool.remove(ob);
            System.out.println("Thread has been removed from the pool");
        }        
    }
    
    public synchronized boolean isProcessCompleted() {
        if (threadPool != null) {
            if (threadPool.size() == 0) {
                return true;
            }
        }          
        return false;
    }
    
    
    public synchronized int getThreadCount() {
        if (threadPool != null) {
            return threadPool.size();
        }          
        return 0;
    }

}

Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger