DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 7 of 7
  1. #1
    Join Date
    May 2005
    Posts
    75

    Question about recursion and threads

    I'm writing a program that requires the answer to use recursion, however, I want to use a Thread so I can see it working.

    How do I pause each iteration of the recursion loop using a Thread?
    Last edited by srekcus; 02-18-2006 at 12:10 AM.

  2. #2
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Recursion is when you have a method, and inside that method you call itself. Here's an example of how to get a specific index of the fibonacci sequence:
    Code:
    public int fib(int n) {
        /* 0th and 1st indexes are 1 */
        if (n == 0 || n == 1) {
            return 1;
        } else {
            /* an index of the fibonacci sequence is the sum of the two previous terms */
            return fib(n - 1) + fib(n - 2);
        }
    }

  3. #3
    Join Date
    May 2005
    Posts
    75
    Thanks, but how do I pause each iteration of the recursion loop using a thread?

  4. #4
    Join Date
    May 2005
    Posts
    75

  5. #5
    Join Date
    Dec 2005
    Location
    New Jersey
    Posts
    290
    Just put Thread.sleep(millisecondsToSleep); in the beginning of the method.

  6. #6
    Join Date
    Feb 2006
    Posts
    25
    Thanks, but how do I pause each iteration of the recursion loop using a thread?
    Here's a simple program that prints 0 to 100 and pauses after each number:

    Code:
    public class Test
    {
       public static void main(String[] args) throws Exception
       {
          for(int x = 0; x < 100; x++)
          {
             System.out.println(x);
             Thread.sleep(1000);
          }
       }
    }
    Thread.sleep(long millis) is what makes it pause, move this where you want your code to pause and it should work. Hope this helps.

    Note that Thread.sleep() throws an InterruptedException.

  7. #7
    Join Date
    May 2005
    Posts
    75
    Cool, thanks!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links