如何同时运行两个方法

时间:2012-03-12 08:52:30

标签: 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);

    }

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

7 个答案:

答案 0 :(得分:14)

你开始两个主题:

试试这个:

// 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块,但上面的代码应该会给您一个良好的开端。)

进一步阅读:

答案 1 :(得分:7)

您最好使用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));

您的Downloader课程必须实施Callable界面。

答案 2 :(得分:3)

您可以使用Thread,并使用多线程在并行上运行这两种方法。您必须覆盖run()并调用Thread.start()

请注意,您必须注意同步方法。

另请注意:只有当您的计算机有2个以上的核心时,您才能获得“真正的并行运行”,但是,如果没有,则操作系统将为您模拟“并行”运行。

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

这就是concurrency and threading的用途。

答案 5 :(得分:0)

你启动两个不同的线程,但如果你至少有一个2核的机器,它们将真正并行运行。 Google Java多线程。

答案 6 :(得分:0)

是的,绝对有可能。但是,多线程或并发编程是一个非常广泛和复杂的主题。

最好从这里开始

http://docs.oracle.com/javase/tutorial/essential/concurrency/