Android中 多線程下載原理,android多線程

來源:互聯網
上載者:User

Android中 多線程下載原理,android多線程

計算每個線程的下載起始終止位置公式如下

檔案讀寫方式4中類型

工程源碼目錄

package cn.itcast.download;import java.io.File;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.URL;public class MulThreadDownloader {    public static void main(String[] args) throws Exception {        String path = "http://219.245.72.241:8080/web3/gaosu.jsp";//伺服器檔案的地址        int threadsize = 3;//開啟三個線程,android應用中開啟的線程數不能太多        new MulThreadDownloader().download(path, threadsize);    }    private void download(String path, int threadsize) throws Exception {        URL downpath = new URL(path);        HttpURLConnection conn = (HttpURLConnection) downpath.openConnection();        conn.setConnectTimeout(5000);        conn.setRequestMethod("GET");        if(conn.getResponseCode() == 200){            int length = conn.getContentLength();//擷取網路檔案的長度            File file = new File(getFileName(path));            RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");//產生本地檔案            accessFile.setLength(length);            accessFile.close();            //計算每條線程負責下載的資料量            int block = length % threadsize == 0 ? length / threadsize : length / threadsize +1;            for(int threadid = 0 ; threadid < threadsize ; threadid++){                new DownloadThread(threadid, downpath, block, file).start();            }        }    }    //負責下載操作    private final class DownloadThread extends Thread{        private int threadid;        private URL downpath;        private int block;        private File file;        public DownloadThread(int threadid, URL downpath, int block, File file) {            this.threadid = threadid;            this.downpath = downpath;            this.block = block;            this.file = file;        }        public void run() {            int startposition = threadid * block;//從網路檔案的什麼位置開始下載資料            int endposition = (threadid+1) * block - 1;//下載到網路檔案的什麼位置結束            //指示該線程要從網路檔案的startposition位置開始下載,下載到endposition位置結束            //Range:bytes=startposition-endposition            try{                RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");                accessFile.seek(startposition);//移動指標到檔案的某個位置                HttpURLConnection conn = (HttpURLConnection) downpath.openConnection();                conn.setConnectTimeout(5000);                conn.setRequestMethod("GET");                conn.setRequestProperty("Range", "bytes="+ startposition+ "-"+ endposition);//地區下載                //分段下載請求碼不是200,而是206                //if(conn.getResponseCode() == 206){                InputStream inStream = conn.getInputStream();                byte[] buffer = new byte[1024];                int len = 0;                while( (len = inStream.read(buffer)) != -1 ){                    accessFile.write(buffer, 0, len);                }                accessFile.close();                inStream.close();                System.out.println("第"+ (threadid+1)+ "線程下載完成");            }catch (Exception e) {                e.printStackTrace();            }        }    }    /**     * 擷取檔案名稱     * @param path 下載路徑     * @return     */    private static String getFileName(String path) {        return path.substring(path.lastIndexOf("/")+ 1);    }}

用戶端要下載伺服器web3目錄裡的gaosu.jsp檔案

啟動tomcat,掛起伺服器web3

運行上面的java程式,結果展示

此時會發現工程源碼目錄下產生了下載完成的gaosu.jsp檔案

聯繫我們

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