Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2005

Tip: Looking for answers? Try searching our database.

Help with threads

Thread view: 
Petterson Mikael - 28 Nov 2005 14:13 GMT
Hi,

From my class I call compute to get the following done:

- create a CalcData object with values for numerator & denominator.
- Create an instance of Calculation()
- Create a new Thread with Calculation as target.
- Start the calculation.
- Then I need to wait for the thread to finnish (unsure about this part).
- Then I fire an event with fireUpdateOccurred(new UpdateEvent( this,
calc.data )).

So what is the problem I have? This works only once. When I try to input
new values and my compute is executed again I get a null as result. I
wonder if the thread did not end gracefully?

Any hints?

cheers,

//mikael

public void compute(String numerator, String denominator){
     CalcData data = new CalcData();
     data.setN(numerator);
     data.setD(denominator);
     //My Runnable class
     Calculation calc = new Calculation(data);
     if (calcThread == null) {
            calcThread = new Thread(calc, "Calculation");
            calcThread.start();
                   
     }
//    Wait for the thread to finish but don't wait longer than a
       // specified time
        long delayMillis = 20000; // since max is 15 seconds delay in
calculation
       try {
           calcThread.join(delayMillis);
   
           if (calcThread.isAlive()) {
               // Timeout occurred; thread has not finished
           } else {
               // Finished
           }
       } catch (InterruptedException e) {
           // Thread was interrupted
       }
     //wait for theard to finnish before we can fireUpdateOccurred.
     fireUpdateOccurred(new UpdateEvent( this, calc.data ));
   
   
  }

CalcData
========
/**
 * This class contains the data in (denominator and nominator) and out
 *  (result) for division used in Exercise2Model.
 * @author eraonel
 *
 */
public class CalcData {
    private boolean available = false;
    private String d, n,r;
   
    public CalcData() {
    }
    public String getD() {
        return d;
    }
    public void setD(String d) {
        this.d = d;
    }
    public String getN() {
        return n;
    }
    public void setN(String n) {
        this.n = n;
    }
    public String getR() {
        return r;
    }
    public void setR(String r) {
        this.r = r;
    }
   
   
   
}

Calculation
===========

import java.util.Random;

public class Calculation implements Runnable {

   
    public CalcData data;
    private static Random generator = new Random();
   
    public Calculation(CalcData data) {
        this.data = data;
    }   
   
    // Here is the actual calculation performed.
    public void run() {
        String result;
             // read two numbers and calculate quotient
             try {
                //pause 5-15 sec. before actual calcuation
                int milliSeconds = (generator.nextInt( 10000 )+5000);
                System.out.println("Pausing of seconds:"+milliSeconds);
                Thread.sleep(milliSeconds);
                Integer n = Integer.parseInt( data.getN() );
                Integer d = Integer.parseInt( data.getD() );
                Integer q = quotient( n, d );
                System.out.println("Calculating");
                result = q.toString();
                data.setR(result);
                System.out.println("Result is :"+result);
       
       
             }

             // process improperly formatted input
             catch ( NumberFormatException numberFormatException )
             {
                   result = "Enter two integers";
             }

             // process attempts to divide by zero
             catch ( ArithmeticException arithmeticException )
             {
                    result = "Division by zero";
             }
             //
             catch (InterruptedException ie){
                    ie.printStackTrace();
                }
             // process unexpected exception
                catch ( Exception exception )
                {
                    result = exception.getMessage();
                }

    }
//
    public Integer quotient( Integer numerator, Integer denominator )
throws ArithmeticException{
             return numerator / denominator;
    }

}
NullBock - 28 Nov 2005 14:47 GMT
What's the point of the exercise?  Do you have a real need to run the
calculations in another thread?  Creating and starting a *single*
thread, and then immediately calling the join() method, seems like a
bit of a waste to me.  Can't you just do the calculations in the main
thread?

For a concrete answer to your question, you cannot call start on the
same thread twice.  According to the Java 1.4 API, and
IllegalThreadStateException is thrown if the thread was already
started.  Testing this on Win32 1.5 doesn't throw an exception, though,
it merely fails quietly.  This is probably why you're getting a null
value.

Walter Gildersleeve
Freiburg, Germany

______________________________________________________
http://linkfrog.net
URL Shortening
Free and easy, small and green.
Petterson Mikael - 28 Nov 2005 14:59 GMT
> What's the point of the exercise?  Do you have a real need to run the
> calculations in another thread?  Creating and starting a *single*
> thread, and then immediately calling the join() method, seems like a
> bit of a waste to me.  Can't you just do the calculations in the main
> thread?

Well the point of the exercise is to have multiple threads doing a
calculation. Later on we will add other tasks so this one cannot occupy
the main thread.

> For a concrete answer to your question, you cannot call start on the
> same thread twice.  According to the Java 1.4 API, and
> IllegalThreadStateException is thrown if the thread was already
> started.  Testing this on Win32 1.5 doesn't throw an exception, though,
> it merely fails quietly.  This is probably why you're getting a null
> value.

Any suggestion on how I can do this?

> Walter Gildersleeve
> Freiburg, Germany
[quoted text clipped - 3 lines]
> URL Shortening
> Free and easy, small and green.
NullBock - 28 Nov 2005 22:53 GMT
Does the thread have to be kept in a field?  Couldn't you simply use a
local variable, creating a thread every time the method is called?
That would avoid the problem of reusing thread objects.

Walter Gildersleeve
Freiburg, Germany

___________________________________________
http://linkfrog.net
URL Shortening
Free and easy, small and green
Petterson Mikael - 29 Nov 2005 15:06 GMT
> Does the thread have to be kept in a field?  Couldn't you simply use a
> local variable, creating a thread every time the method is called?
[quoted text clipped - 7 lines]
> URL Shortening
> Free and easy, small and green

Thanks that was a good thing to do.

//mikael


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.