如何同时运行两个方法
我有这段代码:
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块,但上面的代码应该会给您一个良好的开端。)
进一步阅读:
- Java™教程:课程:并发
您最好使用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
接口。
您可以使用Thread ,并使用multithreading在并行上运行这两种方法。 您将不得不重写run()
并调用Thread.start()
请注意,您必须注意同步方法。
另请注意:只有当您的计算机具有2个以上内核时才会获得“真正的并行运行”,但是,如果没有,则操作系统将为您模拟“并行”运行。
这就是并发和线程的用途。
你启动两个不同的线程,但如果你至少有一个2核的机器,它们将真正并行运行。 Google Javamultithreading。
是的,绝对可能。 但是,multithreading或并发编程是一个非常广泛和复杂的主题。
最好从这里开始
http://docs.oracle.com/javase/tutorial/essential/concurrency/
这就是线程的用途。 线程是一个轻量级的内部进程,用于与“主线程”并行运行代码。
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html