Thread Pool using java 5 and queue

How do we write Thread Pool using java 5.
I want to create Thread Pool from which i should be able to run and queue the task.

I mean that
 
 runThread(Runnable r)
 checkavailableThreadsInPool
 getActiveThreadCount - returns number of active Thread

Any suggestion , sample code?
BHUSHANGEETEAsked:
Who is Participating?
 
BHUSHANGEETEAuthor Commented:
In this we cant control number of threads running now.
0
 
CEHJConnect With a Mentor Commented:
Here's some code i wrote a couple of years ago for EE:


import java.util.PriorityQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Executors;


/**
 *      Description of the Class
 *
 * @author             CEHJ
 * @created            20 February 2005
 */
public class Switch extends PriorityQueue<Packet> {
      /**
       *      Description of the Field
       */
      public final static long serialVersionUID = 0xDEFACE;

      /**
       * Decimal fraction of initial capacity used to calculate
       * the absolute value at boundary (see below)
       */
      private double boundaryLimitAsDecimal;
      /**
       * Absolute value at boundary, calculated by
       * boundaryLimitAsDecimal * initialCapacity
       * e.g. in a Switch with initialCapacity capability
       * of handling 50 packets initially, with a boundaryLimitAsDecimal
       * of 0.5, boundaryLimitAsAbsoluteValue would be 25, i.e. the boundary
       * would be applied at the 25th packet to arrive at the switch
       */
      private int boundaryLimitAsAbsoluteValue;
      /**
       * The priority that must be held by the packet
       * in order to be allowed to enter the switch once
       * the boundary condition is reached
       */
      private int minimumPriorityAtBoundary;
      /**
       * The initial number of packets that the switch
       * is designed to handle, although the switch can
       * grow to accommodate more
       */
      private int initialCapacity;


      /**
       *Constructor for the Switch object
       *
       * @param      initialCapacity                         Intial number of packets allowed into the switch.
       *      Used in calculating the boundary (see below)
       * @param      boundaryLimitAsDecimal      Decimal fraction of initial capacity used to calculate
       * the absolute value at boundary (see above)
       */
      public Switch(int initialCapacity, double boundaryLimitAsDecimal) {
            super(initialCapacity);
            this.initialCapacity = initialCapacity;
            this.boundaryLimitAsDecimal = boundaryLimitAsDecimal;
            boundaryLimitAsAbsoluteValue = (int) (initialCapacity * boundaryLimitAsDecimal);
            System.out.printf("Switch: initial capacity = %d, boundary = element %d\n", initialCapacity, boundaryLimitAsAbsoluteValue);
      }


      /**
       *      Sets the minimumPriorityAtBoundary attribute of the Switch object
       *
       * @param      minimumPriorityAtBoundary      The new minimumPriorityAtBoundary value
       */
      public void setMinimumPriorityAtBoundary(int minimumPriorityAtBoundary) {
            this.minimumPriorityAtBoundary = minimumPriorityAtBoundary;
      }


      /**
       *      Gets the minimumPriorityAtBoundary attribute of the Switch object
       *
       * @return            The minimumPriorityAtBoundary value
       */
      public int getMinimumPriorityAtBoundary() {
            return minimumPriorityAtBoundary;
      }


      /**
       *      If a boundary condition (see above) has been reached, then only
       *      packets of priority < minimumPriorityAtBoundary will be allowed
       *      into the switch. Yes, this is confusing, but the confusion is
       *      grounded in the fact that Sun orders the priorities in a PriorityQueue
       *      such that the lowest numeric values have the highest priority, so we approach
       *      things likewise.
       *
       * @param      packet      The packet arriving at the switch
       * @return                         As per Queue.offer
       */
      public boolean offer(Packet packet) {
            synchronized (this) {
                  System.out.println(this);
                  System.out.println("Head=" + peek());
                  System.out.printf("Offering packet %s to the switch...\n", packet.toString());
                  boolean boundaryCondition = (size() >= boundaryLimitAsAbsoluteValue);
                  if (boundaryCondition) {
                        System.out.println("At boundary condition");
                        if (packet.getPriority() <= minimumPriorityAtBoundary) {
                              System.out.printf("Accepted offer for packet id %d\n", packet.getId());
                              return super.offer(packet);
                        }
                        else {
                              System.out.printf("Refused offer for packet id %d\n", packet.getId());
                              return false;
                        }
                  }
                  return super.offer(packet);
            }
      }


      /**
       *      The main program for the Switch class
       *      Start a Switch with initial capacity of 50
       *      with a boundary condition occurring at half-way
       *      to capacity, i.e. at the 25th packet's arrival
       *
       * @param      args      The command line arguments
       */
      public static void main(String[] args) {
            Switch switch_ = new Switch(50, 0.5);
            switch_.setMinimumPriorityAtBoundary(2);
            new PacketGenerator(switch_, 50, 5).generate();
      }


}

/**
 *      Generate numberOfPackets packets and send them to Switch switch_
 *
 * @author             CEHJ
 * @created            20 February 2005
 */
class PacketGenerator {


      private ThreadFactory packetFactory;
      private Switch switch_;
      private int minPriority;
      private int numberOfPackets;



      /**
       *Constructor for the PacketGenerator object
       *
       * @param      switch_                              The target switch
       * @param      numberOfPackets      Number of packets to generate
       * @param      minPriority                  Upper number for priority, which is
       * in fact the lowest priority
       */
      public PacketGenerator(Switch switch_, int numberOfPackets, int minPriority) {
            this.switch_ = switch_;
            this.numberOfPackets = numberOfPackets;
            this.minPriority = minPriority;
            packetFactory = Executors.defaultThreadFactory();
      }


      /**
       *      Description of the Method
       */
      public void generate() {
            for (int i = 0; i < numberOfPackets; i++) {
                  packetFactory.newThread(new Packet(switch_, i, (int) (Math.random() * minPriority))).start();
            }
      }
}

/**
 *      Description of the Class
 *
 * @author             CEHJ
 * @created            20 February 2005
 */
class Packet implements Comparable, Runnable {


      private static int MAX_SLEEP_DURATION = 5000;
      private int priority;
      private int id;
      private Switch switch_;



      /**
       *Constructor for the Packet object
       *
       * @param      switch_       The switch targeted by this packet
       * @param      id                        Description of the Parameter
       * @param      priority      Description of the Parameter
       */
      public Packet(Switch switch_, int id, int priority) {
            this.switch_ = switch_;
            this.id = id;
            this.priority = priority;
      }


      /**
       *      Gets the priority attribute of the Packet object
       *
       * @return            The priority value
       */
      public int getPriority() {
            return priority;
      }


      /**
       *      Gets the id attribute of the Packet object
       *
       * @return            The id value
       */
      public int getId() {
            return id;
      }


      /**
       *      Description of the Method
       *
       * @param      o      Description of the Parameter
       * @return            Description of the Return Value
       */
      public int compareTo(Object o) {
            Packet otherPacket = (Packet) o;
            return priority - otherPacket.priority;
      }


      /**
       *      Sleeps for a random time before hitting the switch
       */
      public void run() {
            // Sleep for random time
            try {
                  Thread.sleep((int) (Math.random() * MAX_SLEEP_DURATION));
                  switch_.offer(this);
            }
            catch (Exception e) {
                  e.printStackTrace();
            }
      }


      /**
       *      Description of the Method
       *
       * @return            Description of the Return Value
       */
      public String toString() {
            return String.format("<[id=%d,priority=%d]", id, priority);
      }

}
0
 
Computer101Commented:
Forced accept.

Computer101
EE Admin
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.