Android菜鳥之路-多線程下載

來源:互聯網
上載者:User

Android菜鳥之路-多線程下載
Android用戶端下載步驟在Android用戶端首先建立一個空檔案(空白檔案),大小跟伺服器的一模一樣。開啟若干線程,分別去下載伺服器上對應的資源。如果所有的線程都下載完畢,伺服器的資源就下載完畢。Android用戶端下載邏輯

擷取到伺服器端資源檔的大小(connection.getContentLength())

String path = "http://localhost:8080/ff.exe";URL url = new URL(path);// 擷取連結HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 參數connection.setRequestMethod("GET");connection.setConnectTimeout(5000);// 響應碼int responseCode = connection.getResponseCode();if (responseCode == 200) {    // 得到服務端返回的檔案大小    long contentLength = connection.getContentLength();    System.out.println("伺服器檔案大小:"+contentLength);}// 中斷連線connection.disconnect();

在本地建立一個大小和伺服器一樣的的空白檔案

File file = new File("temp.ext");RandomAccessFile raf= new RandomAccessFile(file, "rw");raf.setLength(contentLength);

根據開啟線程的數量,把伺服器資源給等分成若干份(threadCount:線程數量)

假設檔案大小是10個byte。(長度:length)假設3個線程(線程數量:threadCount)。 int blockSize = length / threadCount;線程1 下載3個byte    1-3     0 * blockSize + 1 ~ 1 * blockSize線程2 下載3個byte    4-6     1 * blockSize + 1 ~ 2 * blockSize 線程3 下載4個byte    7-10    2 * blockSize + 1 ~ 3 * blockSize(length)// 開啟若干個子線程,分別去下載對應的資源long threadCount = 3;long blockSize = contentLength / threadCount;for (int i = 1; i <= threadCount; i++) {    // 計算下載起始、結束位置    long startIndex = (i - 1) * blockSize + 0;// 伺服器也是從0開始    long endIndex = i * blockSize - 1; //    // 最後一個線程    if (i == threadCount) {        endIndex = contentLength - 1;    }    System.out.println("開啟線程:" + i + ",下載的位置:(" + startIndex + "~"            + endIndex + ")");    new DownloadThread(i, startIndex, endIndex, path).start();}

建立線程類

static class DownloadThread extends Thread {    private int threadId;    private long startIndex;    private long endIndex;    private String path;    public DownloadThread(int threadId, long startIndex, long endIndex,            String path) {        super();        this.threadId = threadId;        this.startIndex = startIndex;        this.endIndex = endIndex;        this.path = path;    }    public void run() {        URL url;        try {            url = new URL(path);            // 擷取連結            HttpURLConnection connection = (HttpURLConnection) url                    .openConnection();            // 參數            connection.setRequestMethod("GET");            connection.setConnectTimeout(5000);            // 告訴伺服器下載的參數            connection.setRequestProperty("Range", "bytes=" + startIndex                    + "-" + endIndex);            // 響應碼            int responseCode = connection.getResponseCode();            System.out.println("伺服器狀態代碼:" + responseCode);            // 下載伺服器檔案,返回的是206            if (responseCode == 206) {                InputStream inputStream = connection.getInputStream();                File file = new File("temp.exe");                RandomAccessFile raf = new RandomAccessFile(file, "rw");                // 指定檔案開始寫的位置                raf.seek(startIndex);                System.out.println("第" + threadId + "個線程,寫檔案的開始、結束位置("                        + (startIndex) + "," + (endIndex) + ")");                int len = 0;                 byte[] buf = new byte[1024];                while ((len = inputStream.read(buf)) != -1) {                    raf.write(buf, 0, len);                }                inputStream.close();                raf.close();                System.out.println("第" + threadId + "個線程下載完畢了");            }        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.