Java–多線程下載

來源:互聯網
上載者:User
package com.jwzhangjie;/** * 說明: * 每一個線程下載的位置計算方式: * 開始位置: * (線程id - 1)*每一塊大小 * 結束位置: * (線程id*每一塊大小) - 1  *  ---注意有時候不一定能夠整除,所以最後一個線程的結束位置應該是檔案的末尾 *   *  步驟: *  1.本地建立一個大小跟伺服器檔案相同的臨時檔案 *  2.計算分配幾個線程去下載伺服器上的資源,知道每個線程下載檔案的位置 *  3.開啟三個線程,每一個線程下載對應位置的檔案 *  4.如果所有的線程,都把自己的資料下載完畢後,伺服器上的資源都被下載到本地了 */import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class Demo {public static String path = "http://softdownload.hao123.com/hao123-soft-online-bcs/soft/Y/2013-07-18_YoudaoDict_baidu.alading.exe";public static int threadCount = 3;public static void main(String[] args) throws Exception{//1.串連伺服器,擷取一個檔案,擷取檔案的長度,在本地建立一個跟伺服器一樣大小的臨時檔案URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");int code = conn.getResponseCode();if (code == 200) {//伺服器端返回的資料的長度,實際上就是檔案的長度int length = conn.getContentLength();System.out.println("檔案總長度:"+length);//在用戶端本地建立出來一個大小跟伺服器端一樣大小的臨時檔案RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");//指定建立的這個檔案的長度raf.setLength(length);raf.close();//假設是3個線程去下載資源。//平均每一個線程下載的檔案大小.int blockSize = length / threadCount;for (int threadId = 1; threadId <= threadCount; threadId++) {//第一個線程下載的開始位置int startIndex = (threadId - 1) * blockSize;int endIndex = threadId * blockSize - 1;if (threadId == threadCount) {//最後一個線程下載的長度要稍微長一點endIndex = length;}System.out.println("線程:"+threadId+"下載:---"+startIndex+"--->"+endIndex);new DownLoadThread(path, threadId, startIndex, endIndex).start();}}else {System.out.printf("伺服器錯誤!");}}/** * 下載檔案的子線程  每一個線程下載對應位置的檔案 * @author jie * */public static class DownLoadThread extends Thread{private int threadId;private int startIndex;private int endIndex;/** * @param path 下載檔案在伺服器上的路徑 * @param threadId 線程Id * @param startIndex 線程下載的開始位置 * @param endIndex線程下載的結束位置 */public DownLoadThread(String path, int threadId, int startIndex, int endIndex) {super();this.threadId = threadId;this.startIndex = startIndex;this.endIndex = endIndex;}@Overridepublic void run() {try {URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection)url.openConnection();conn.setConnectTimeout(5000);conn.setRequestMethod("GET");//重要:請求伺服器下載部分檔案 指定檔案的位置conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);//從伺服器請求全部資源返回200 ok如果從伺服器請求部分資源 返回 206 okint code = conn.getResponseCode();System.out.println("code:"+code);InputStream is = conn.getInputStream();//已經設定了請求的位置,返回的是當前位置對應的檔案的輸入資料流RandomAccessFile raf = new RandomAccessFile("setup.exe", "rwd");//隨機寫檔案的時候從哪個位置開始寫raf.seek(startIndex);//定位檔案int len = 0;byte[] buffer = new byte[1024];while ((len = is.read(buffer)) != -1) {raf.write(buffer, 0, len);}is.close();raf.close();System.out.println("線程:"+threadId+"下載完畢");} catch (Exception e) {e.printStackTrace();}}}}

將源碼添加到一個java工程裡面就可以了,為了真實下載,我將自己搭建的伺服器替換為網路有效連結,進行測試,列印資訊如下:

檔案總長度:5577744線程:1下載:---0--->1859247線程:2下載:---1859248--->3718495線程:3下載:---3718496--->5577744code:206code:206code:206線程:2下載完畢線程:1下載完畢線程:3下載完畢

之後我會封裝一個介面,其實迅雷等下載軟體下載原理也是這樣的,每一個伺服器對下載的請求都有頻寬節流設定的,所以多個線程下載從整體上是增加了下載的頻寬,不過啟動的線程也不是沒有限制的,這個受限於你的真實的物理頻寬。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.