2016-02-06 77 views
0

我怎么能一次下载2到3个文件,当1完成它拾取另一个?现在它可以完成它需要做的事情,但是如果一次下载30个视频,则需要一段时间,所以我希望它一次下载2或3个视频。如何一次完成多个任务?

try { 
      URL url; 
      byte[] buf; 
      int byteRead, byteWritten = 0; 
      url = new URL(getFinalLocation(fAddress));; 
      outStream = new BufferedOutputStream(new FileOutputStream(destinationDir + "\\" + localFileName)); 

      uCon = url.openConnection(); 
      is = uCon.getInputStream(); 
      buf = new byte[size]; 
      while ((byteRead = is.read(buf)) != -1) { 
       outStream.write(buf, 0, byteRead); 
       byteWritten += byteRead; 
      } 
      System.out.println("Downloaded Successfully."); 
      //System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :" + byteWritten); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
       outStream.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
+0

尝试线程 - https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html – radoh

回答

2

您可以将该代码添加到实现Runnable的类中。代码将采用方法run()。 (您需要为每个可运行接口实施该方法。)

然后,您创建新线程并开始传递您的可运行子线程。

Thread thread = new Thread(new RunnableClass()); 
thread.start(); 

你需要实现某种逻辑传递fAddress字符串到RunnableClass。 (通过构造函数或在thread.start()之前调用的方法。)

这是否帮助您开始?

编辑 - 添加例如

public class Main { 

    public static void main(String[] args) { 

     Thread thread1 = new Thread(new MyRunnable("http://someaddress")); 
     thread1.start(); 

     Thread thread2 = new Thread(new MyRunnable("http://otheraddress")); 
     thread2.start(); 

    } 

    public static class MyRunnable implements Runnable { 

     String address; 

     public MyRunnable(String address) { 
      this.address = address; 
     } 

     @Override 
     public void run() { 
      // My code here that can access address 
     } 
    } 
} 
+0

我是这么认为的,我我会看看这些文件,看看发生了什么,但是它给了我一些方向 –

+0

@ J.Doe,我已经添加了一个例子来进一步说明如何做到这一点。 – jheimbouch

+0

谢谢,真的有帮助 –

相关问题