Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run two methods simultaneously

Tags:

java

I have this piece of code:

public static void main(String[] args) {
        Downoader down = new Downoader();
        Downoader down2 = new Downoader();
        down.downloadFromConstructedUrl("http:xxxxx", new File("./references/word.txt"), new File("./references/words.txt"));
        down2.downloadFromConstructedUrl("http:xxxx", new File("./references/word1.txt"), new File("./references/words1.txt"));
        System.exit(0);

    }

Is it possible to run these two methods: down.downloadFromConstructedUrl() and down2.downloadFromConstructedUrl() simultaneously? If so, how?

like image 574
RazorMx Avatar asked Mar 12 '12 08:03

RazorMx


1 Answers

You start two threads:

Try this:

// Create two threads:
Thread thread1 = new Thread() {
    public void run() {
        new Downloader().downloadFromConstructedUrl("http:xxxxx",
                       new File("./references/word.txt"),
                       new File("./references/words.txt"));
    }
};

Thread thread2 = new Thread() {
    public void run() {
        new Downloader().downloadFromConstructedUrl("http:xxxxx",
                       new File("./references/word1.txt"),
                       new File("./references/words1.txt"));
    }
};

// Start the downloads.
thread1.start();
thread2.start();

// Wait for them both to finish
thread1.join();
thread2.join();

// Continue the execution...

(You may need to add a few try/catch blocks, but the above code should give you a good start.)

Further reading:

  • The Java™ Tutorials: Lesson: Concurrency
like image 154
aioobe Avatar answered Oct 11 '22 14:10

aioobe