單線程下載最大的問題是頻寬用不滿,而且一旦中斷就得從頭來過。多執行緒下載的思路其實很樸素:先問伺服器檔案有多大,把檔案切成好幾段,每條執行緒只下載自己那一段,最後各自寫進同一個檔案的對應位置。
package my.Thread;
import java.io.BufferedInputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CountDownLatch;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ManyThreadActivity extends Activity {
private Button button;
private TextView textView;
private static final int THREAD_COUNT = 4;
private CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
private long completeLength = 0;
private long fileLength;
public static String SaveFile = Environment.getExternalStorageDirectory()
+ "/DownFile/" + "test.Mp3";
public static final String url = "https://210.30.12.33:8080/mp3/Beyond.mp3";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.editText1);
textView.setText(url);
button.setOnClickListener(new MyListener());
}
class MyListener implements OnClickListener {
@Override
public void onClick(View v) {
try {
download(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 進行下載的執行緒 */
class DownloadThread extends Thread {
private URL url;
private RandomAccessFile file;
private long from;
private long end;
DownloadThread(URL url, RandomAccessFile file, long from, long end) {
this.url = url;
this.file = file;
this.from = from;
this.end = end;
}
@Override
public void run() {
try {
long pos = from;
byte[] buf = new byte[1024 * 8];
HttpURLConnection cn = (HttpURLConnection) url.openConnection();
// 設定請求的起始與結束位置
cn.setRequestProperty("Range", "bytes=" + from + "-" + end);
BufferedInputStream bis = new BufferedInputStream(cn.getInputStream());
int len;
while ((len = bis.read(buf)) > 0) {
synchronized (file) {
file.seek(pos);
file.write(buf, 0, len);
}
pos += len;
completeLength += len;
System.out.println(completeLength * 100 / fileLength + "%");
}
cn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
latch.countDown();
}
}
public void download(String address) throws Exception {
URL url = new URL(address);
URLConnection cn = url.openConnection();
fileLength = cn.getContentLength();
long packageLength = fileLength / THREAD_COUNT; // 每條執行緒要下載的位元組數
long leftLength = fileLength % THREAD_COUNT; // 除不盡的餘數
RandomAccessFile file = new RandomAccessFile(SaveFile, "rw");
System.out.println(fileLength);
long pos = 0;
for (int i = 0; i < THREAD_COUNT; i++) {
long endPos = pos + packageLength;
new DownloadThread(url, file, pos, endPos).start();
if (leftLength > 0) { // 把餘數平均分給前面的執行緒
endPos++;
leftLength--;
}
pos = endPos;
}
latch.await(); // 等待四條執行緒全部收尾
}
}
先用 getContentLength() 拿到總長度,除以執行緒數得到每段大小,餘數則從第一段開始逐一 +1 分掉,確保四段首尾相接、剛好覆蓋整個檔案。每條執行緒寫入前都用 synchronized (file) 保護 seek 與 write 這組動作,因為 RandomAccessFile 的「移動指標」和「寫入」是兩個步驟,若不鎖住,交錯執行就會寫錯位置。
範例把下載直接寫在 onClick 裡,真機上會被主執行緒網路限制擋下,應該另外開執行緒;寫檔前也要確認 /DownFile/ 目錄存在並已取得外部儲存空間讀寫權限。此外,completeLength 由多條執行緒共同累加,嚴格來說應該改用 AtomicLong 或加鎖;若想支援續傳,只要把「已下載長度」持久化,重來時從該偏移送出 Range 即可。範例最終會把內容存成 test.mp3。