public class MultiThreadDown {
static int ThreadCount = 4;
static String path = "http://192.168.1.104:8080/android/pdf.exe";
static long start = 0;
public static void main(String[] args) throws Exception {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
// 1.先獲取請求資源的大小
int length = conn.getContentLength();
File file = new File("m.mpg");
// 生成臨時文件
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
// 設置臨時文件的大小
raf.setLength(length);
raf.close();
// 計算每個線程應該要下載多少個字節
int size = length / ThreadCount;
start = System.currentTimeMillis();
for (int i = 0; i < ThreadCount; i++) {
// 計算線程下載的開始位置和結束位置
int startIndex = i * size;
int endIndex = (i + 1) * size - 1;
// 如果是最后一個線程,那么結束位置寫死
if (i == (ThreadCount - 1)) {
endIndex = length - 1;
}
new DownThread(startIndex, endIndex, i).start();
}
}
}
}
class DownThread extends Thread {
int startIndex;
int endIndex;
int threadId;
public DownThread(int startIndex, int endIndex, int threadId) {
super();
this.startIndex = startIndex;
this.endIndex = endIndex;
this.threadId = threadId;
}
@Override
public void run() {
// 再次發送HTTP請求,下載源文件
try {
URL url = new URL(MultiThreadDown.path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
// 設置請求的數據的區間
conn.setRequestProperty("Range", "bytes=" + startIndex + "-"
+ endIndex);
// 請求部分數據,響應碼為206
if (conn.getResponseCode() == 206) {
// 此時只有 1/threadcount數據
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
int len = 0;
long total = 0;
File file = new File("m.mpg");
RandomAccessFile raf = new RandomAccessFile(file, "rwd");
// 把文件的寫入位置移動至startIndex
raf.seek(startIndex);
while ((len = is.read(b)) != -1) {
// 每次讀取流里的數據寫入臨時文件
raf.write(b, 0, len);
total += len;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
android 多線程下載原理
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
- 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
推薦閱讀更多精彩內容
- 1.普通單線程下載文件: 直接使用URLConnection.openStream();打開網絡輸入流,然后將流寫...
- 一、為什么要使用多線程,多線程真的能提高效率嗎? 1.1為什么要使用多線程 多線程編程的目的,就是"最大限度地利用...
- 效果圖 白話分析: 多線程:肯定是多個線程咯斷點:線程停止下載的位置續傳:線程從停止下載的位置上繼續下載,直到完成...
- 最近項目需要一個下載模塊,要求多任務多線程斷點下載還要通知欄提示,網上找了很多都沒合適的,后面下了xutil做 成...
- 楊過一生有三個父親,生父楊康,義父歐陽鋒和精神上的父親郭靖。尤其歐陽鋒和楊過的關系,其實是金庸在神雕中布下的一個局...