我怎么能一次下载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 :(得分:2)
您可以将该代码添加到实现Runnable
的类中。代码将放在方法run()
中。 (您需要根据可运行的接口实现该方法。)
然后创建新线程并启动它们传递runnable。
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
}
}
}