1 2 Previous Next 17 Replies Latest reply on Dec 1, 2003 8:27 AM by 807595

    Help with thread...

    807595
      Hello, im trying to write a thread program that uses a vector to find which #'s are Prime and which are not (using boolean true=prime). My problem is that im stuck on how to create a thread for my vector to work. It has to loop through the vector and if it is a prime, to launch the thread and in the thread set the elements to false for all multiples of the number. ex: 2(4,6,8..)
      This is what I have so far...
      import java.util.*;
      import java.awt.*;
      import javax.swing.*;
      
      
      public class Prime {
      
              public static void main( String [] args )
              {
      
                Vector v = new Vector();
      
                try{
                           //populate vector with 100 "true" elements.
                         for (int i = 0; i < 101; i++)
                       {
                       v.add(new Boolean(true));
                          }
                          //print out 100 Boolean elements (all true)
                          for (int i = 0; i < v.size(); i++)
                       {
                          System.out.println(v.get(i));
                          }
                //---------------------------------------------------------
                          for (int i = 0; i < v.size(); i++)
                         {
                               System.out.println(v.elementAt(i));
                          }
      And the code to do find the prime #'s is:
      public boolean isItPrime(int number) {
                boolean isPrime = true;
                if (number%2=0 && number >2){ //if number is even, return false
                isPrime=false;
                return isPrime;
                }
                for (i=3;i<=(number/2);i=i+2) { //if number is evenly divided by an ood
                if (number%i = 0){isPrime=false;break;} //set isPrime to false
                }
                return isPrime;
                }
      Any help would be very much appreciated...thank you! :)
        • 1. Re: Help with thread...
          807595
          I am not sure if this answers your question, but here is a boolean search for Primes that works well.
          private void findPrimes (String num) {                
          int top = Integer.parseInt(num) + 1; //sets a top variable, which is one higher than the higher number examining
                         //The +1 is so the array has enough spaces, since index 0 counts as one. Each index will represent its number.  ie. index 3 is number 
          boolean[ ] primes = new boolean[top]; //a bool array, the size of how many the user indicated
          primes[2]=true; //the first prime is 2.  0 and 1 are not prime by default
                             for (int j=3; j<top; j=j+2) //This forLoop sets all the odd numbers to true, these are the numbers that might be prime
                                  primes[j] = true; //sets current index to true, which is an odd number
                             //This forNext loop is the main code which determains if a number is prime.  Its basic functionality is this:
                             //The outer loop goes from 3 until i gets too large to divide into any other numbers in the list
                             //If the current number is a prime, it tests it with other possible primes in the list
                             //inc is the amount that will be increased each time to look for other primes, it calculates the lowest possible number that needs to be checked, which is i doubled
                             //The inner loop goes through the list, starting with the current test times itself, which is the next possible prime.  In then increases by inc until it checks the entire list
                             for(int i=3; i*i<top; i++) { //Goes through all the indexies until i gets to big to be a factor of any other number
                                     if(primes==true) { //if i is a prime number, start with its square and look for more primes
          int inc = i * 2; //The amount of increase should be twice that of i
          for(int j= i*i; j < top; j=j+inc) //any number that is a factor of the tested number is not Prime, and any number that is twice the number also is not prime
          primes[j]=false; //the number isn't prime
          }
          }



          I know it is confusing, I hope the comments help. Basically, this function takes a number and finds all the primes, 2-num.
          • 2. Re: Help with thread...
            807595
            Thanks for the help...but im really more interested in how i can create and call the thread to do that procedure for each # from 1 to 100 and indicate it in the vector if its true or false. Can anyone write me the code on how to start and put that prime checker in the thread to check??/
            • 3. Re: Help with thread...
              807595
              No help i guess??? :(
              • 4. Re: Help with thread...
                807595
                To create and start a thread you could write a small helper class that extends Thread.
                The constructor for this class should take whatever information you require to do your operation - eg your vector of numbers, and the prime that you are looking for multiples of.
                You will also need to implement a run() method in this class that will do the search for multiples.
                To set things off... When your main loop finds a prime, create a new instance of your helper class (the one that extends Thread), handing it the prime, and a reference to your vector. Call start() on the new instance to make the new thread execute the run() method that you wrote.

                Hope this helps
                • 5. Re: Help with thread...
                  807595
                  I tried what you said...and it compiles but it doesn't output what I want.... Can someone check my code and see where my problems are...been looking at it for several hours playing around with it...thanks in advanced! :)
                  import java.util.*;
                  import java.awt.*;
                  import javax.swing.*;
                  
                  public class primetest
                  {
                       public static void main(String[] args)
                       {
                            Vector v = new Vector();
                  
                                 //populate vector with 100 "true" elements.
                                 for (int i = 0; i < 101; i++)
                                 {
                                    v.add(new Boolean(true));
                                 }
                                 //print out 100 Boolean elements (all true)
                                 //for (int i = 0; i < v.size(); i++)
                                 //{
                                 //     System.out.println(v.get(i));
                                 //}
                                 //---------------------------------------------------------
                                 for (int i = 2; i < v.size(); i++)
                                 {
                                      PrimeThread thread1 = new PrimeThread(v, i);
                                      thread1.start();
                                 }
                  
                       }//end main
                  } //end class primetest
                  
                  //class PrimeThread controls thread execution
                  class PrimeThread extends Thread
                  {
                       private int num;
                       private Vector primeVector;
                       public PrimeThread(Vector v, int i)
                       {
                  
                       num = i;
                       primeVector = v;
                  
                       // here the constructor calls the vector of numbers, and the prime that im looking for multiples of.
                  
                  
                       }
                       // method run is the code to be executed by new thread
                       public void run()
                       {
                            //loop through vector, if element is prime (i), launch a thread for the # in that thread
                            //and set all the multiples for that # to false.
                  
                            try
                            {
                  
                                 for (int j=num+num; j < 100; j+=num)
                                      {
                                           primeVector.set(j, new Boolean(false));
                                      }
                  
                            }
                            catch (Exception exception)
                            {
                            exception.printStackTrace();
                            }
                  
                       System.err.println("Done...");
                       //when all the threads except the main thread have ended, print the numbers for which it is still true
                       //Output should start 1,2,3,5,7 and so on....Print 20 numbers per line.
                       //HOW DO YOU DO THIS??
                       for (int i = 0; i < primeVector.size(); i++)
                                 {
                                           System.out.println(""+(Boolean)primeVector.get(i).booleanValue());
                                 }
                  
                       } //end run
                  }// end class PrimeThread
                  • 6. Re: Help with thread...
                    807595
                    You are creating a PrimeThread for each element in the vector. From your original post you only want to do this if the loop index is prime.

                    The printout bit at the end should be done by the main thread. To do this you will have to make the main thread keep a count of the number of threads it creates and do a wait() until they are all finished.

                    Each PrimeThread should call a method in the primetest class when it is finished. This new method should decrement the active thread count, and notify the main thread if the count drops to zero (is being called by the last active thread).
                    • 7. Re: Help with thread...
                      807595
                      Can you show me by using or fixing up my code please...im confused???
                      • 8. Re: Help with thread...
                        807595
                        It's maybe best that I don't write all the code for you, but I'll try and explain better what it is exactly you will need to make this work. You can also look up the java API docs for more info on Object.wait() and Object.notify() if necessary.

                        First you have to work out what the threads are going to do.

                        Main Thread.

                        Initialise the vector.
                        Start a PrimeThread for each prime index into the vector, making sure that you count the number of threads started.
                        Wait for all of the PrimeThreads to finish.
                        Print out the contents of the vector.

                        PrimeThread
                        Loop through the vector, setting indexes into the vector to false.
                        Notify the main thread that a prime thread has finished.

                        How to do it.

                        Add a counter (lets call it activeThreads) to the primetest class to allow us to keep track of the number of PrimeThreads that are active.

                        Add three synchronized methods to the primetest class. The methods have to be synchronized because they are going to be used by multiple threads to modify and check the activeThreads count, and may also call wait() or notify().

                        private synchronized void addActiveThread()
                        private synchronized void waitForActiveThreads()
                        public synchronized void removeActiveThread()

                        addActiveThread() should just increment the activeThreads count. It should be called just before you call start() on a new PrimeThread instance.

                        waitForActiveThreads() should be called by the main thread after it has finished starting all the necessary PrimeThreads. It should check the value of activeThreads and call wait() if activeThreads > 0.

                        removeActiveThread() should be called just before PrimeThread.run() returns. You will have to pass a reference to your primetest instance to the PrimeThread constructor to allow it to call this method. It should decrement the activeThreads count and call notify() if activeThreads is zero.
                        • 9. Re: Help with thread...
                          807595
                          Oops,

                          One thing that I didn't notice was that you are doing all the primetest work in main, which is of course static.
                          To make this work you will have to alter what your current main() method does. One way would be to move the code within main() to a non static method within primetest (doTest() for example). main() would then simply construct a new primetest() and call the doTest() method (or whatever it is you called it).

                          Appologies for any confusion this may have caused you. I'm assuming you know the difference between static and non static methods.
                          • 10. Re: Help with thread...
                            807595
                            This is what i understood from what you explained....
                            import java.util.*;
                            import java.awt.*;
                            import javax.swing.*;
                            
                            public class primetest
                            {
                                 private int countThread = 0;
                                 private int k = 0;
                            
                                 public static void main(String[] args)  throws InterruptedException
                                 {
                                           //init the vector
                                           Vector v = new Vector();
                            
                                           //populate vector with 100 "true" elements.
                                           for (int i = 0; i < 101; i++)
                                           {
                                              v.add(new Boolean(true));
                                           }
                                           // start a PrimeThread for each prime index into the vector, making sure you count
                                           //the number of threads started
                                           for (int k; k < v.size(); k++)
                                           {
                                                // search through index
                                                if (((Boolean)v.elementAt(k)).booleanValue())
                                                {
                                                     countThread++;
                                                     PrimeThread thread1 = new PrimeThread(v,k);
                            
                                                }
                            
                                           }
                                           //print out the contents of the vector...20 #'s per line...
                                           for (int i = 0; i < v.size(); i++)
                                           {
                                                     //System.out.println(""+(Boolean)v.get(i).booleanValue());
                                           }
                            
                                 }//end main
                            } //end class primetest
                            
                            //class PrimeThread controls thread execution
                            class PrimeThread extends Thread
                            {
                            
                                 private int activeThreads = 0;
                            
                                 public PrimeThread(Vector v, int i)
                                 {
                                      addActiveThread();
                                      for (int j=i+i; j<v.size();j+=i)
                                      {
                                           v.set(j,new Boolean(false));
                                      }
                                      primetest.main();
                            
                                 }
                                 private synchronized void addActiveThread()
                                 {
                                      activeThreads++;
                                      Thread.start();
                            
                                 }
                                 private synchronized void waitForActiveThread()
                                 {
                                      if (activeThreads > 0)
                                      Thread.wait();
                            
                                 }
                                 public synchronized void removeActiveThread()
                                 {
                                      if (activeThreads == 0)
                                     Thread.notify();
                                 }
                                 // method run is the code to be executed by new thread
                                 public void run()
                                 {
                            
                            
                                 System.err.println("Done...");
                            
                            
                                 } //end run
                            }// end class PrimeThread
                            It does not compile cause there are error which i do not know how to fix...can you take a look at it and tell me where i have fix the places or if my concept is right??? Thanks for th help people... :)
                            • 11. Re: Help with thread...
                              807595
                              Updated....
                              import java.util.*;
                              import java.awt.*;
                              import javax.swing.*;
                              
                              public class primetest
                              {
                              
                                   private int k = 0;
                              
                                   public static void main(String[] args) throws InterruptedException
                                   {
                                             //init the vector
                                             Vector v = new Vector();
                                             int countThread = 0;
                                             //populate vector with 100 "true" elements.
                                             for (int i = 0; i < 101; i++)
                                             {
                                                v.add(new Boolean(true));
                                             }
                                             // start a PrimeThread for each prime index into the vector, making sure you count
                                             //the number of threads started
                                             for (int k; k < v.size(); k++)
                                             {
                                                  // search through index
                                                  if (((Boolean)v.elementAt(k)).booleanValue())
                                                  {
                                                       countThread++;
                                                       PrimeThread(v,k);
                                                       PrimeThread.waitForActiveThread();
                              
                                                  }
                              
                                             }
                                             //print out the contents of the vector...20 #'s per line...
                                             for (int i = 0; i < v.size(); i++)
                                             {
                                                       //System.out.println(""+(Boolean)v.get(i).booleanValue());
                                             }
                              
                                   }//end main
                              } //end class primetest
                              
                              //class PrimeThread controls thread execution
                              class PrimeThread extends Thread
                              {
                              
                                   private int activeThreads = 0;
                                   Vector vector;
                                   int i;
                                   public PrimeThread(Vector vector, int i)
                                   {
                                        addActiveThread(i);     //make new thread
                                        this.vector = vector;
                                        this.i = i;
                                        // make false multiples of the prime index found in main.....ex: 2(4,6,8...)
                                        for (int j=i+i; j<vector.size();j+=i)
                                        {
                                             vector.set(j,new Boolean(false));
                                        }
                                        primetest.main();     //call main to proceed with string
                              
                                        removeActiveThread();          //call to remove count of threads
                              
                              
                                   }
                                   private synchronized void addActiveThread(int i)
                                   {
                                        activeThreads++;     //add 1 to thread count
                                        PrimeThread p = new PrimeThread(i);  //create new thread
                                        new Thread(p).start();     //run public PrimeThread method to get rid of multiples
                              
                              
                                   }
                                   private synchronized void waitForActiveThread()
                                   {
                                        if (activeThreads > 0)  //if there are active threads..it has to wait til it completes
                                        Thread.wait();
                              
                                   }
                                   public synchronized void removeActiveThread()
                                   {
                                        activeThreads--;   //decrement 1 from count of thread
                                        if (activeThreads == 0)          //if no more threads...notify
                                       Thread.notify();
                                   }
                                   // method run is the code to be executed by new thread
                                   public void run()
                                   {
                              
                              
                                   System.err.println("Done...");
                              
                              
                                   } //end run
                              }// end class PrimeThread
                              Errors:
                              C:\Java\primetest.java:34: cannot resolve symbol
                              symbol : method PrimeThread (java.util.Vector,int)
                              location: class primetest
                                                       PrimeThread(v,k);
                              ^
                              C:\Java\primetest.java:35: waitForActiveThread() has private access in PrimeThread
                                                       PrimeThread.waitForActiveThread();
                              ^
                              C:\Java\primetest.java:67: main(java.lang.String[]) in primetest cannot be applied to ()
                                        primetest.main();     //call main to proceed with string
                              ^
                              C:\Java\primetest.java:76: cannot resolve symbol
                              symbol : constructor PrimeThread (int)
                              location: class PrimeThread
                                        PrimeThread p = new PrimeThread(i); //create new thread
                              ^
                              C:\Java\primetest.java:84: non-static method wait() cannot be referenced from a static context
                                        Thread.wait();
                              ^
                              C:\Java\primetest.java:91: non-static method notify() cannot be referenced from a static context
                                   Thread.notify();
                              • 12. Re: Help with thread...
                                807595
                                I get no compile errors now but when i run it...I get nothing on the screen....it pauses for a bit and then ends...Any help out there????
                                import java.util.*;
                                import java.awt.*;
                                import javax.swing.*;
                                
                                public class Prime2
                                {
                                
                                
                                     public static void main(String[] args) throws InterruptedException
                                     {
                                               //init the vector
                                               Vector v = new Vector();
                                               int countThread = 0;
                                               //populate vector with 100 "true" elements.
                                               for (int i = 0; i < 101; i++)
                                               {
                                                  v.add(new Boolean(true));
                                               }
                                               // start a PrimeThread for each prime index into the vector, making sure you count
                                               //the number of threads started
                                               for (int k=2; k < v.size(); k++)
                                               {
                                                    // search through index
                                                    if (((Boolean)v.elementAt(k)).booleanValue())
                                                    {
                                                         countThread++;
                                                         PrimeThread p = new PrimeThread(v,k);  //create new thread
                                                         new Thread(p).start();     //run public PrimeThread method to get rid of multiples
                                                         //PrimeThread.waitForActiveThread();
                                
                                                    }
                                
                                               }
                                               //print out the contents of the vector...20 #'s per line...
                                               for (int i = 0; i < v.size(); i++)
                                               {
                                                         System.out.println(v.elementAt(i));
                                               }
                                
                                     }//end main
                                } //end class primetest
                                
                                //class PrimeThread controls thread execution
                                class PrimeThread extends Thread
                                {
                                
                                     private int activeThreads = 0;
                                     Vector vector;
                                     int i;
                                     public PrimeThread(Vector vector, int i)
                                     {
                                          addActiveThread(i);     //make new thread
                                          this.vector = vector;
                                          this.i = i;
                                          // make false multiples of the prime index found in main.....ex: 2(4,6,8...)
                                          for (int j=i+i; j<vector.size();j+=i)
                                          {
                                               vector.set(j,new Boolean(false));
                                          }
                                          //Prime2.main();     //call main to proceed with string
                                          waitForActiveThread();
                                          removeActiveThread();          //call to remove count of threads
                                
                                
                                     }
                                     private synchronized void addActiveThread(int i)
                                     {
                                          activeThreads++;     //add 1 to thread count
                                     }
                                     private synchronized void waitForActiveThread()
                                     {
                                          try
                                          {
                                               if (activeThreads > 0)  //if there are active threads..it has to wait til it completes
                                               wait();
                                          }
                                          catch(Exception e)
                                          {
                                               System.out.println(e);
                                          }
                                     }
                                     public synchronized void removeActiveThread()
                                     {
                                          try
                                          {
                                               activeThreads--;   //decrement 1 from count of thread
                                               if (activeThreads == 0)          //if no more threads...notify
                                              notify();
                                          }
                                          catch(Exception e)
                                          {
                                          System.out.println(e);
                                          }
                                
                                     }
                                     // method run is the code to be executed by new thread
                                     public void run()
                                     {
                                
                                
                                     System.err.println("Done...");
                                
                                
                                     } //end run
                                }// end class PrimeThread
                                • 13. Re: Help with thread...
                                  807595
                                  Someone please help me...it compiles but no data gets displayed???? :(
                                  import java.util.*;
                                  import java.awt.*;
                                  import javax.swing.*;
                                  
                                  public class primetest
                                  {
                                       private int activeThread = 0;
                                  
                                       private synchronized void addActiveThread()
                                            {
                                                 activeThread++;     //add 1 to thread count
                                            }
                                            private synchronized void waitForActiveThread()
                                            {
                                                 try{
                                                 if (activeThread > 0)  //if there are active threads..it has to wait til it completes
                                                 wait();
                                                 }
                                                 catch(InterruptedException exception)
                                                 {
                                                      exception.printStackTrace();
                                                 }
                                            }
                                            public synchronized void removeActiveThread(int activeThread)
                                            {
                                                 activeThread--;   //decrement 1 from count of thread
                                                 if (activeThread == 0)          //if no more threads...notify
                                                notify();
                                            }
                                            public void doTest()
                                            {
                                            //init the vector
                                                 Vector v = new Vector();
                                  
                                                 //populate vector with 100 "true" elements.
                                                 for (int i = 0; i < 101; i++)
                                                 {
                                                    v.add(new Boolean(true));
                                                 }
                                                 // start a PrimeThread for each prime index into the vector, making sure you count
                                                 //the number of threads started
                                                 for (int k=2; k < v.size(); k++)
                                                 {
                                                      // search through index
                                                      if (((Boolean)v.elementAt(k)).booleanValue())
                                                      {
                                                           PrimeThread thread = new PrimeThread(v,k);
                                                           addActiveThread();
                                                           thread.start();
                                                      }
                                                 waitForActiveThread();
                                                 }
                                  
                                                 //print out the contents of the vector...20 #'s per line...
                                                 for (int i = 0; i < v.size(); i++)
                                                 {
                                                           System.out.println(v.elementAt(i));
                                                 }
                                            }
                                  
                                       public static void main(String[] args)
                                       {
                                                 new primetest();
                                  
                                       }//end main
                                  } //end class primetest
                                  
                                  //class PrimeThread controls thread execution
                                  class PrimeThread extends Thread
                                  {
                                  
                                       private Vector v;
                                       private int i;
                                       public PrimeThread(Vector v, int i)
                                       {
                                  
                                            v = v;
                                            i = i;
                                  
                                  
                                       }
                                  
                                       public void run()
                                       {
                                            //int count=0;
                                            for (int j=i+i; j < v.size();j+=i)
                                            {
                                                 //count++;
                                                 v.set(j,new Boolean(false));
                                            }
                                            //count--;
                                            //removeActiveThread(count);
                                            System.out.println("Done..");
                                  
                                       } //end run
                                  }// end class PrimeThread
                                  • 14. Re: Help with thread...
                                    807595
                                    public static void main(String[] args)     {               
                                         primetest self = new primetest();     
                                         self.doTest();
                                    }//end main
                                    You created a new instance of primetest, but never called doTest(). I am not sure if the rest of your code is right, but make something display on the screen at least.
                                    1 2 Previous Next