Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 04-06-2012, 01:01 PM   PM User | #1
dan-dan
Regular Coder

 
dan-dan's Avatar
 
Join Date: Aug 2009
Location: England
Posts: 483
Thanks: 22
Thanked 79 Times in 78 Posts
dan-dan is on a distinguished road
Confused over Thread.sleep()

I've just written a couple of classes from what I'm reading and I'm not entirely sure what the purpose of Thread.sleep() is in this program.
I know it pauses the program and throws an exception if disturbed, but I can't get my head around what it's actually achieving.

Could someone enlighten me please. Thank you.

Main class with sleep()
PHP Code:
public class PrimeThreads {
    public static 
void main(String[] args) {
        
PrimeThreads pt = new PrimeThreads(args);
    }
    
    public 
PrimeThreads(String[] args) {
        
PrimeFinder[] finder = new PrimeFinder[args.length];
        for (
int i 0args.lengthi++) {
            try {
                
long count Long.parseLong(args[i]);
                
finder[i] = new PrimeFinder(count);
                
System.out.println("Looking for prime " count);    
            } catch (
NumberFormatException nfe) {
                
System.out.println("Error: " nfe.getMessage());
            }
        }
        
boolean complete false;
        while (!
complete) {
            
complete true;
            for (
int j 0finder.lengthj++) {
                if (
finder[j] == null) continue;
                if (!
finder[j].finished) {
                    
complete false;
                } else {
                    
displayResult(finder[j]);
                    
finder[j] = null;
                }
            }
            try {
                
Thread.sleep(1000);
            } catch (
InterruptedException ie) {
                
// Do nothing
            
}
        }
    }
    private 
void displayResult(PrimeFinder finder) {
        
System.out.println("Prime " finder.target
                
" is " finder.prime);
    }


Thread class performing calculation:
PHP Code:
public class PrimeFinder implements Runnable {
    public 
long target;
    public 
long prime;
    public 
boolean finished false;
    private 
Thread runner;
    
    
PrimeFinder(long inTarget) {
        
target inTarget;
        if (
runner == null) {
            
runner = new Thread(this);
            
runner.start();
        }
    }
    
    public 
void run() {
        
long numPrimes 0;
        
long candidate 2;
        while (
numPrimes target) {
            if (
isPrime(candidate)) {
                
numPrimes++;
                
prime candidate;
            }
            
candidate++;
        }
        
finished true;
    }
    
    
boolean isPrime(long checkNumber) {
        
double root Math.sqrt(checkNumber);
        for (
int i 2<= rooti++) {
            if (
checkNumber == 0)
                return 
false;
        }
        return 
true;
    }

dan-dan is offline   Reply With Quote
Old 04-06-2012, 03:10 PM   PM User | #2
ckeyrouz
Senior Coder

 
ckeyrouz's Avatar
 
Join Date: Jun 2009
Location: Montreal, Canada
Posts: 1,044
Thanks: 5
Thanked 179 Times in 179 Posts
ckeyrouz is on a distinguished road
First of all the Thread.sleep(1000) command forces the main process which is the one generated from the execution of PrimeThreads to wait (sleep) for 1 second (1000 milliseconds). If another thread tries to wake him up before the sleep time is over it will throw an InterruptedException.

However in your case, there does not seem to be another thread (at least visible in the code you posted) so this exception won't be thrown.

That is the main purpose of the sleep in general.

In your case I cannot see any usage for it. In fact we use the sleep method whenever we need the main thread to wait for another operation to be completed or to give a small wait time between two sequential operations. In the code you posted, the sleep is last command so I think it is useless.

I got other comments for your code:

the while loop "while(!complete) only runs once because you are setting the complete to true in the first line of the while block. So it is a one iteration loop. An if statement would have been enought

Code:
if(!complete) {

complete = true;

etc.. etc.. etc..

}
Hope this was clear.
__________________
Software and cathedrals are much the same - first we build them, then we pray.
ckeyrouz is offline   Reply With Quote
Users who have thanked ckeyrouz for this post:
dan-dan (04-06-2012)
Old 04-06-2012, 04:32 PM   PM User | #3
dan-dan
Regular Coder

 
dan-dan's Avatar
 
Join Date: Aug 2009
Location: England
Posts: 483
Thanks: 22
Thanked 79 Times in 78 Posts
dan-dan is on a distinguished road
Thank you for your response.

This is actually straight out the book I'm reading 'Sams Teach Yourself Java 6'. And it does only consist of the two classes above.

I 'sort of' got the point of Thread.sleep(), I just didn't get what it was doing here! I too thought being the last command that it's doing nothing, but I'm only starting out so thought I'd check.

Thanks again.
dan-dan is offline   Reply With Quote
Old 04-06-2012, 04:34 PM   PM User | #4
dan-dan
Regular Coder

 
dan-dan's Avatar
 
Join Date: Aug 2009
Location: England
Posts: 483
Thanks: 22
Thanked 79 Times in 78 Posts
dan-dan is on a distinguished road
I'll have to have a look into that while loop too. Cheers
dan-dan is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 08:37 AM.


Advertisement
Log in to turn off these ads.