【问题标题】:Why the use of Threads doesn't speed up my program? Java [duplicate]为什么使用线程不能加快我的程序? Java [重复]
【发布时间】:2018-11-09 10:37:37
【问题描述】:

我对多处理还很陌生,我想知道在多个文件的下载中使用它们有多方便。 基本上,我有一个应用程序(完全可以从 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();
        }
     }
}

【问题讨论】:

  • 在您的情况下,您的实际带宽可能是瓶颈。顺序或并行,单位时间内可以传输的数据量是有限制的。
  • 如果你的速度受限于网络,多线程根本无济于事。

标签: java multithreading url download threadpool


【解决方案1】:

使用 Thread.start 代替 Thread.run

澄清一下:你执行了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();
        }
    }
}

【讨论】:

  • 谢谢,是的,这是问题所在。
猜你喜欢
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 1970-01-01
  • 2011-02-22
  • 1970-01-01
相关资源
最近更新 更多