Albert
Albert

Reputation: 151

Two Loops at almost the same time

i don't what this process is called, but i've seen that it's possible. what is this process called?

basically, i have a method that has a loop, and in every iteration has a delay second.

function myLoop(float delay)
{
    for(int x=0; x<100; x++)
    {
        Print("Loop number: " + x);
        TimeDelay(delay);
    }
}

i'd like to run the second instance without waiting until the first instance is finished.

function main()
{
     myLoop(2);
     myLoop(2);
}

so once the first myLoop started, i'd like the second myLoop to start immediately, they would be both running at the same time, my question is, what do you call this process? is this process possible?(in java for example).

Thank you very much! :)

Upvotes: 2

Views: 3033

Answers (4)

Emanuel Landeholm
Emanuel Landeholm

Reputation: 1408

This is called an asynchronous computation. You can solve this cleanly with Futures. (You don't really need to do full-blown multithreading)

http://download.oracle.com/javase/6/docs/api/java/util/concurrent/Future.html

Upvotes: 0

Abu Sithik
Abu Sithik

Reputation: 287

The answer for your questions.

  1. What is this called? A: Threading - running multiple tasks at a same time. (We call it as forking in PHP/Linux applications.)

  2. Is this possible in Java? A: Offcourse this is possible. To be frank this is more easier to implement in Java. Please follow the above answers.

Upvotes: 0

rkg
rkg

Reputation: 5719

Java implementation of your program will be similar to this.

    class MyThread implements Runnable{
       Thread t;
       int delay;
       MyThread (int delay) {
          t = new Thread(this,"My thread");
          this.delay = delay;
          t.start();
       }
       public void run() {
          for(int x=0; x<100; x++)
          {
           Print("Loop number: " + x);
           TimeDelay(delay);
          }
      }
    }
    class Demo {
       public static void main (String args[]){
         Thread t1 = new MyThread(2);
         Thread t2 = new MyThread(2);
         t1.join();
         t2.join();    
       }
    }

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564433

This typically requires some form of multithreading.

You would do something like:

function main
    start thread, calling myLoop(2)
    start thread, calling myLoop(2)

    ' Potentially wait for threads to complete
end function

For details on how this works in Java, see the Concurrency Tutorial.

Upvotes: 2

Related Questions