如何同时运行两个方法 [英] How to run two methods simultaneously

查看:161
本文介绍了如何同时运行两个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

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()同时?如果是这样,怎么样?

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

推荐答案

你开始两个主题:

试试这个:

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

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

进一步阅读:

  • The Java™ Tutorials: Lesson: Concurrency

这篇关于如何同时运行两个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆