如何同时运行两个方法

Raz*_*rMx 8 java

我有这段代码:

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

    }
Run Code Online (Sandbox Code Playgroud)

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

aio*_*obe 16

你开始两个线程:

试试这个:

// 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...
Run Code Online (Sandbox Code Playgroud)

(您可能需要添加一些try/catch块,但上面的代码应该会给您一个良好的开端.)

进一步阅读:


Pet*_*aný 8

您最好使用ExecutorService,而不是直接使用线程,并通过此服务运行所有下载任务.就像是:

ExecutorService service = Executors.newCachedThreadPool();

Downloader down = new Downloader("http:xxxxx", new File("./references/word.txt"), new File("./references/words.txt"));
Downloader down2 = new Downloader("http:xxxx", new File("./references/word1.txt"), new File("./references/words1.txt"));

service.invokeAll(Arrays.asList(down, down2));
Run Code Online (Sandbox Code Playgroud)

你的Downloader类必须实现Callable接口.


Aur*_*bon 0

这就是线程的用途。线程是一个轻量级内部进程,用于与“主线程”并行运行代码。

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html