为什么使用线程不能加快我的程序速度?爪哇岛



我对多处理很陌生,我想知道在多文件下载中使用它们有多方便。基本上,我有一个应用程序(可以完美地从URL下载文件(图像、视频…((,我想加快下载速度(现在它们是顺序的(,将它们拆分到多个线程上。因此,我创建了一个类"PrimeThread"来覆盖线程类的run方法,并在每次下载时都在main中运行一个thread实例,但我没有注意到任何时间加速性能。这是我写的代码(主要(:

for(int e = 0;e<videos.size();e++) //for every video i create a new thread
{
PrimeThread thread= new PrimeThread(downloader,path1,path2);
thread.run();
}

以下是我在Thread类中编写的代码:

import java.io.IOException;
class PrimeThread extends Thread {
HttpDownloadUtility scaricatore; //instance of the "downloader" class 
String path1, path2;
PrimeThread(HttpDownloadUtility scaricatore,String path1,String path2) {
this.scaricatore = scaricatore;
this.path1 = path1;
this.path2 = path2;
}
public void run() {
try {
scaricatore.downloadMedia(path1, path2); //method of the "downloader" class that takes 2 paths in input and downloads from the 1st and put the file downloaded in the 2nd path
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

使用线程.启动而不是线程.运行

澄清一下:您执行了方法PrimeThread.run,这只是一个普通的方法,它是同步执行的。这意味着,在循环中,下一次"运行"仅在上一次完成之后运行。您可以安全地删除"扩展线程",您的程序将编译并运行得很好。

Thread类真正的"魔力"在于方法"start"。JVM以一种特殊的方式处理它。它在操作系统级别创建一个线程,并开始执行您放入"运行"中的任何代码。

顺便说一句,从类Thread扩展并不是一个好的做法。相反,您应该定义要在类中运行的代码,该类实现java.lang.Runnable并使用Thread构造函数new Thread(Runnable(。

主回路:

for(int e = 0;e<videos.size();e++) //for every video i create a new thread
{
Thread thread= new Thread(new PrimeRunnable(downloader,path1,path2));
thread.start();
}

可运行:

class PrimeRunnable implements Runnable {
HttpDownloadUtility scaricatore; //instance of the "downloader" class
String path1, path2;
PrimeRunnable(HttpDownloadUtility scaricatore,String path1,String path2) {
this.scaricatore = scaricatore;
this.path1 = path1;
this.path2 = path2;
}
public void run() {
try {
scaricatore.downloadMedia(path1, path2); //method of the "downloader" class that takes 2 paths in input and downloads from the 1st and put the file downloaded in the 2nd path
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

最新更新