我有这段代码:

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);

    }

是否可以同时运行这两种方法:down.downloadFromConstructedUrl()down2.downloadFromConstructedUrl()?如果是这样,怎么办?

最佳答案

您启动两个线程:

试试这个:

// 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...

(您可能需要添加一些try/catch块,但是上面的代码应该为您提供一个良好的开端。)

进一步阅读:
  • The Java™ Tutorials: Lesson: Concurrency
  • 09-11 06:31