Link to home
Create AccountLog in
Avatar of flo0ona
flo0ona

asked on

Java code (Two threads + prime numbers)

Hi all,

I have a problem with my java code.. and I need help

I have to write a java program that implements two threads, they must share a static variable in mutual exclusive. The first thread must randomly generate prime numbers between 1-101, then save the first one in a static variable and wait, once the number is produced, the second thread print it and goes to waiting state to give turn to the first thread to produce another prime number.

The program must produce 10 prime numbers.



I have gotten the code for thread:

public class ThreadTester {

   // create and start threads
   public static void main( String args[] )
   {
      PrintThread thread1, thread2, thread3, thread4;

      // create four PrintThread objects
      thread1 = new PrintThread( "thread1" );
      thread2 = new PrintThread( "thread2" );
      thread3 = new PrintThread( "thread3" );
      thread4 = new PrintThread( "thread4" );

      System.err.println( "\nStarting threads" );

      // start executing PrintThreads
      thread1.start();
      thread2.start();
      thread3.start();
      thread4.start();

      System.err.println( "Threads started\n" );
   }

}  // end class ThreadTester

// Each object of this class picks a random sleep interval.
// When a PrintThread executes, it prints its name, sleeps,
// prints its name again and terminates.
class PrintThread extends Thread {
   private int sleepTime;

   // PrintThread constructor assigns name to thread
   // by calling superclass Thread constructor
   public PrintThread( String name )
   {
      super( name );

      // sleep between 0 and 5 seconds
      sleepTime = (int) ( Math.random() * 5000 );

      // display name and sleepTime
      System.err.println(
         "Name: " + getName() + ";  sleep: " + sleepTime );
   }

   // control thread's execution
   public void run()
   {
      // put thread to sleep for a random interval
      try {
         System.err.println( getName() + " going to sleep" );

         // put thread to sleep
         Thread.sleep( sleepTime );
      }

      // if thread interrupted during sleep, catch exception
      // and display error message
      catch ( InterruptedException interruptedException ) {
         System.err.println( interruptedException.toString() );
      }

      // print thread name
      System.err.println( getName() + " done sleeping" );
   }

}  // end class PrintThread




Then for prime number I have gotten the following code, and I am not sure if it is ok to be used in thread:


import java.math.*;
import java.util.*;

class CreatePrime
{
  public static void main( String args[]) {
    int bitLength = 128;
    int certainty = 10;

    BigInteger prime = new BigInteger( bitLength, certainty, new Random());
    System.out.println( prime.toString());
    }
}



plz, is there any one who is expert in java??? I couldn't link the code I have together, may be I am wrong..

So plz I have no time and need the help within a day..


Avatar of imladris
imladris
Flag of Canada image

The objective you list is to have *two* threads (not 4 or 5). One to be the prime generator, and one to be the printer.

So, the prime generator thread needs to be in a thread. Something like:

import java.math.*;
import java.util.*;

class CreatePrime extends Thread
{  String name;

   public void CreatePrime(String nm)
    {   name=nm;
        return;
    }

  public void run(){
    int bitLength = 128;
    int certainty = 10;
    int num=10;
    int i;

    // produce 10 primes
    for(i=0; i<10; ++i){
        BigInteger prime = new BigInteger( bitLength, certainty, new Random());
        }
    } // end run
}


So i would expect you to have a single main method that creates two threads and then runs them. Something like:

public class ThreadTester {

   // create and start threads
   public static void main( String args[] )
   {
      PrintThread pthread;

      // create threads
      nthread=new CreatePrime("nthread");
      pthread = new PrintThread( "pthread" );

      System.err.println( "\nStarting threads" );

      // start executing PrintThreads
      pthread.start();
      nthread.start();

      System.err.println( "Threads started\n" );
   }

}  // end class ThreadTester



So, now have you a main method, which starts the two threads you need. Now you need to connect up the two threads. As indicated the first one must in fact assign its primes to a static variable and then stall until the print thread picks it up.

Creating a static variable is simply a matter of declaration:

static BigInteger sprime;

Regulating access to it is a matter of using synchronized methods for access, and managing a (static) boolean variable to indicate whether there is a prime ready to be read or not.

The prime (producer) method must use a synchronized method to assign the value to the static and set a flag indicating there is a valid value there. It must also check if the "value there" flag is already set (indicating that the print thread has not yet removed the last one) and, if so, stall with a call to the "wait" method (provided as part of the Object class).

The printthread (consumer) similarly needs a synchronized static method (in the producer class) to remove the value from the static. This method must check the "value there" flag and if there is no value there it must stall with a wait call until one arrives.

Finally, to allow the print thread access to the primethread object, you will have to pass a reference to the prime object into the print object. Something like:

   public static void main( String args[] )
   {
      PrintThread pthread;

      // create threads
      nthread=new CreatePrime("nthread");
      pthread = new PrintThread( "pthread" ,nthread);

You will have to look up how wait works. It operates in conjunction with calls to notify.
Avatar of flo0ona
flo0ona

ASKER

imladris, Thank you soooooooooooo much

You really helped me..

But still I have problem

I implemented the code in this way:



import java.math.*;
import java.util.*;
import java.*;
import javax.swing.*;

class CreatePrime extends Thread
{

   String name;

   public void CreatePrime(String nm)
    {   name=nm;
        return;
    }

  public void run(){
    int bitLength = 128;
    int certainty = 10;
    int num=10;
    int i;

    // produce 10 primes
    for(i=0; i<10; ++i){
        BigInteger prime = new BigInteger( bitLength, certainty, new Random());
        }
    } // end run
}


//main method that creates two threads and then runs them

public class ThreadTester2 {

   // create and start threads
   public static void main( String args[] )
   {
      PrintThread pthread;

      // create threads
      nthread=new CreatePrime("nthread");
      pthread = new PrintThread( "pthread" );

      System.err.println( "\nStarting threads" );

      // start executing PrintThreads
      pthread.start();
      nthread.start();

      System.err.println( "Threads started\n" );
   }

}  // end class ThreadTester


//Creating a static variable

//static BigInteger sprime;



//pass a reference to the prime object into the print object


   public static void main(String args[])

    {
   PrintThread pthread;

     // create threads
    nthread = new CreatePrime("nthread");
    pthread = new PrintThread("pthread", "nthread");

   }


but I still have error:

'class' or 'interface' expected at line 64 , which is  public static void main(String args[])


So can you do me a favour and tell me how I can make the code error free and then how to compile and run it???

because also when I made it error free and compiled it using


javac ThreadTester2.java

I still have problem



Thank you again for your great help
ASKER CERTIFIED SOLUTION
Avatar of imladris
imladris
Flag of Canada image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer