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 l开发者_如何学编程ike 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! :)
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.
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();
}
}
The answer for your questions.
What is this called? A: Threading - running multiple tasks at a same time. (We call it as forking in PHP/Linux applications.)
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.
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
精彩评论