1 Replies - 2457 Views - Last Post: 11 October 2012 - 06:41 AM Rate Topic: -----

#1 desijoker  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 09-May 12

How can i Initilise PrimeRacers before anyworker Thread is Started?

Posted 11 October 2012 - 12:23 AM

Hi All,

i would like to know how can i initialise all the primeRacers before any worker thread is started. In the following code:


package primea2;  
  
import java.util.*;  
  
public class PrimeRace extends Thread {  
    // This code is adapted from A. Turner, "AtomicInteger, Volatile, Synchronized and Raw:  
    // Performance and Safety", NerdsCentral blogspot, 24 November 2011.  Available:   
    // http://nerds-central.blogspot.co.nz/2011/11/atomicinteger-volatile-synchronized-and.html  
      
    private static int timeLimit = 0; // how long the "race" will run, in milliseconds  
    private static PROutputs pROutput = new PROutputs(); // all outputs from all primeRacer worker threads  
    private volatile static boolean finished = false; // the finish flag -- polled by primeRacer worker threads  
      
    // instance variables for primeRacers  
        // Note: primeRacers are worker threads which execute the run() method of the PrimeRace class  
    private int blocksize;   
    private String pName;  
    private int pLane;  
    private PrimeGeneratorInterface pg;   
    private ArrayList<Integer> pList; // the list of primes generated by this primeRacer  
      
    public PrimeRace( ) {  
        // Note: the instance variables of primeRacers are initialized by main().  
    }  
      
    public void run() {  
        while( !finished ) {  
            pList = pg.generateAnotherBlockOfPrimes( blocksize ); // generate primes as fast as possible  
        }  
        pROutput.postResults( pLane, pList ); // report a list of primes, then terminate.  
    }  
      
    public static void main( String[] args ) {  
              
        // references to our PrimeRacers  
        ArrayList<Thread> primeRacerThreads = new ArrayList<Thread>();  
        ArrayList<String> primeRacerNames = new ArrayList<String>();  
  
        //Check arguments, entering them into argvec  
        ArrayList<Integer> argvec = null;   
        try{   
            argvec = checkArgs( args );    
        } catch (Exception e) {   
            System.out.println("Usage: PrimeRace t n1 b1 n2 b2 ... ni bi");   
            System.out.println(" -- where t is the time limit, in milliseconds, for this computation;");  
            System.out.println(" -- ni is the prime number generation method used by the i-th worker thread,");  
            System.out.println(" ---- ni = 1, for a Sieve of Eratosthenes");  
            System.out.println(" ---- ni = 2, for a naive algorithm in Goetz's Introduction to Java threads");  
            System.out.println(" ---- ni = 3, for a probabilistic prime finder in Java.math.BigInteger");  
            System.out.println(" -- bi is the blocksize: the number of ints to be checked for primality");  
            System.out.println("       by ni, between its polls of the time-limit flag");  
            System.out.println(" -- Note that a large bi value makes it more likely that the i-th thread");  
                        System.out.println("       will win the race to generate the most primes, because it will finish");  
            System.out.println("       checking its current block of ints for primality before terminating.");  
            System.exit(1);  
        }   
          
        // construct the primeRacers by interpreting the argvec  
        Iterator<Integer> i = argvec.iterator();  
  
        // the first arg is the timeLimit (a class variable)  
        timeLimit = i.next();  
          
        // the remaining args are method# and blocksize parameters for each primeRacer  
        int lane = 0;   
        while( i.hasNext() ) {  
              
            lane++;  // add a new lane  
            pROutput.addLane();  
              
            // instantiate and initialize a new primeRacer  
            PrimeRace t = new PrimeRace( );    
            t.pLane = lane;  
            switch( i.next() ) {  
                case 1:           
                    t.pName = "Eratosthenes" + lane;  
                    t.pg = new EratosthenesGen();  
                    break;  
                case 2:  
                    t.pName = "Naive" + lane;  
                    t.pg = new NaiveGen();  
                    break;  
                case 3:  
                    t.pName = "JavaMath" + lane;  
                    t.pg = new JavaMathGen();  
                    break;  
            }  
            t.blocksize = i.next();  
      
            // main() needs to have a list of all racer threads, for the join().  
            // All racers will be terminated by the time main() prints the results,   
            // so main() also keeps a list of names  
            primeRacerThreads.add( t );  
            primeRacerNames.add( t.pName );  
              
            // t is now ready to run -- it's on the "starting block" of our racecourse  
              
            // There's no "starting gun"!! primeRacers start as soon as they're ready.    
            // Nobody said this would be a fair race ;-)  
            t.start();   
        }  
  
        // All primeRacers have been started.  The main thread sleeps until the end of the race.  
        try {   
            Thread.sleep( timeLimit );  
        }   
        catch (InterruptedException e) {   
            System.out.println("Interrupted Exception to sleep() was ignored in main()!");  
            // If the println() above produces any console output, then this fall-through is unsafe.  
            // But, most likely, the exception was raised by a ^c console input that is terminating the  
            // entire JVM -- in which case, the println() above will not produce any console output and main()  
            // will be abnormally terminated very soon.  
        }   
          
        // Time's up!  All primeRacers will stop generating primes after they finish their current block  
        finished = true;   
          
        System.out.println("The race is over.  Waiting for primeRunners to finish & report..." );  
        long tFinish = System.currentTimeMillis();  
          
        // The main thread waits (patiently and trustingly ;-) for all racers to terminate.  
        Iterator<Thread> j = primeRacerThreads.iterator();  
        int pc = 1;  
        while( j.hasNext() ) {  
            try {  
                j.next().join(); // blocks main() until racer #j has stopped running  
                System.out.println( "The primeRunner in lane " + pc + " joined main() "  
                            + (System.currentTimeMillis()-tFinish)  
                            + " msec after the race was over." );  
            } catch (InterruptedException e){  
                System.out.println("Interrupted Exception to join() was ignored in main()!");  
                // If the println() above produces any console output, then this fall-through is unsafe.  
                // However it's most likely that the exception was raised by a ^c console input which is terminating the  
                // entire JVM -- in which case, the println() above will not produce any console output and main()  
                // will be abnormally terminated very soon.  
            }  
        }  
          
        // Who won?  Was there any disagreement on which numbers are prime?  
        Iterator<String> kn = primeRacerNames.iterator();  
        Iterator<ArrayList<Integer>> kp = pROutput.get().iterator();  
        while( kp.hasNext() ) {  
            ArrayList<Integer> kl = kp.next();  
            if( kl.size() <= 5 ) {  
                System.out.println( kn.next() + ":" + kl.toString() + ". Found "   
                        + kl.size() + " primes." );               
            } else {  
                Iterator<Integer> kpp = kl.iterator();  
                System.out.println( kn.next() + ": " + kpp.next() + ", " + kpp.next() + ", " + kpp.next() +  
                        " ... " + kl.get( kl.size() - 2 ) + ", " + kl.get( kl.size() - 1 ) + ". Found "   
                        + kl.size() + " primes." );  
            }  
        }  
  
        System.out.println("The fastest primeRunner was in lane " + pROutput.lanesOfLongestLists().toString() );  
        System.out.println("Most primes found: " + pROutput.longest() );  
        System.out.println("Least primes found: " + pROutput.shortest() );  
    } // end main  
      
    public static ArrayList<Integer> checkArgs( String [] args ) throws Exception {   
        // Validate input, copying it into argvec  
        // Note: this is a static method, so main() can access it easily.  (Worker threads  
        // don't use this routine.)  
        ArrayList<Integer> argvec = new ArrayList<Integer>();  
        // There must be an odd number of args >= 3: at least one worker thread  
        if( (args.length %2 != 1) || (args.length < 3) ) {  
            throw new Exception();  
        } else {   
            // read args into argvec, checking bounds  
            for( int i=0; i<args.length; i++ ) {  
                Integer a = Integer.valueOf(args[i]); // todo: an exception is possible here, is it handled correctly?  
                if( a <= 0 ) { // all inputs must be greater than zero   
                    throw new Exception();  
                } else if ( (i%2 == 1) && (( a < 1) || ( a > 3)) ) { // 1 <= ni <= 3, for all i  
                    throw new Exception();  
                } else {  
                    argvec.add( a );  
                }  
            }  
        }  
        return argvec;  
    } //end checkArgs  
} 


Is This A Good Question/Topic? 0
  • +

Replies To: How can i Initilise PrimeRacers before anyworker Thread is Started?

#2 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 866
  • View blog
  • Posts: 2,657
  • Joined: 29-July 11

Re: How can i Initilise PrimeRacers before anyworker Thread is Started?

Posted 11 October 2012 - 06:41 AM


// instantiate and initialize a new primeRacer 
072
            PrimeRace t = new PrimeRace( );   
073
            t.pLane = lane; 
074
            switch( i.next() ) { 
075
                case 1:          
076
                    t.pName = "Eratosthenes" + lane; 
077
                    t.pg = new EratosthenesGen(); 
078
                    break; 
079
                case 2: 
080
                    t.pName = "Naive" + lane; 
081
                    t.pg = new NaiveGen(); 
082
                    break; 
083
                case 3: 
084
                    t.pName = "JavaMath" + lane; 
085
                    t.pg = new JavaMathGen(); 
086
                    break; 
087
            } 
088
            t.blocksize = i.next(); 
089
       
090
            // main() needs to have a list of all racer threads, for the join(). 
091
            // All racers will be terminated by the time main() prints the results,  
092
            // so main() also keeps a list of names 
093
            primeRacerThreads.add( t ); 
094
            primeRacerNames.add( t.pName ); 
095
               
096
            // t is now ready to run -- it's on the "starting block" of our racecourse 
097
               
098
            // There's no "starting gun"!! primeRacers start as soon as they're ready.   
099
            // Nobody said this would be a fair race ;-) 
100
            t.start();  



I won't write the code for you, but don't immediately call start() when creating and adding them to your primeRacerThreads ArrayList. When they're all added, iterate over the list and call start() on each one.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1