java多線程下載執行個體詳解_java

來源:互聯網
上載者:User

本文執行個體講述了java多線程下載。分享給大家供大家參考,具體如下:

使用多線程下載檔案可以更快完成檔案的下載,多線程下載檔案之所以快,是因為其搶佔的伺服器資源多。如:假設伺服器同時最多服務100個使用者,在伺服器中一條線程對應一個使用者,100條線程在電腦中並非並發執行,而是由CPU劃分時間片輪流執行,如果A應用使用了99條線程下載檔案,那麼相當於佔用了99個使用者的資源,假設一秒內CPU分配給每條線程的平均執行時間是10ms,A應用在伺服器中一秒內就得到了990ms的執行時間,而其他應用在一秒內只有10ms的執行時間。就如同一個水龍頭,每秒出水量相等的情況下,放990毫秒的水肯定比放10毫秒的水要多。

多線程下載的實現過程:

1.首先得到下載檔案的長度,然後設定本地檔案的長度。

HttpURLConnection.getContentLength();RandomAccessFile file = new RandomAccessFile("youdao.exe","rw");file.setLength(filesize);//設定本地檔案的長度

2.根據檔案長度和線程數計算每條線程下載的資料長度和下載位置。如:檔案的長度為6M,線程數為3,那麼,每條線程下載的資料長度為2M,每條線程開始下載的位置如下圖所示。

3.使用Http的Range頭欄位指定每條線程從檔案的什麼位置開始下載,如:指定從檔案的2M位置開始下載檔案,代碼如下:

複製代碼 代碼如下:
HttpURLConnection.setRequestProperty("Range", "bytes=2097152-");

4.儲存檔案,使用RandomAccessFile類指定每條線程從本地檔案的什麼位置開始寫入資料

RandomAccessFile threadfile = new RandomAccessFile("<span style="font-family: Arial, Helvetica, sans-serif;">youdao.exe</span><span style="font-family: Arial, Helvetica, sans-serif;"> ","rw");</span>threadfile.seek(2097152);//從檔案的什麼位置開始寫入資料

下面是通過具體實作類別:

在寫實作類別之前我們首先要將要下載的檔案放在伺服器上並部署:

我是放在了這裡 D:\Tomcat\apache-tomcat-7.0.37\webapps\doudou目錄下,並啟動D:\Tomcat\apache-tomcat-7.0.37\bin下的startup.bat

1.DownLoadTest.java

package www.csdn.net.down;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.RandomAccessFile;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class DownLoadTest { public File file; public RandomAccessFile accessFile; // 線程的數量 public static int threadNum = 3; // 每個線程負責下載的大小 int blockSize; // 建立訪問的路徑 public String path = "http://localhost:8080/doudou/youdao.exe"; public static int threadCount;// 數量 public void testDown() {  try {   // 建立出URL對象   URL url = new URL(path);   // 建立出 HttpURLConnection對象   HttpURLConnection httpURLConnection = (HttpURLConnection) url     .openConnection();   // 設定 發請求發送的方式   httpURLConnection.setRequestMethod("GET");   // 佈建要求是否逾時時間   httpURLConnection.setConnectTimeout(5000);   // 設定   httpURLConnection     .setRequestProperty("User-Agent",       " Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");   // 是否響應成功   if (httpURLConnection.getResponseCode() == 200) {    // 擷取檔案的大小    int size = httpURLConnection.getContentLength();    System.out.println("檔案的大小" + size);    // 建立檔案    file = new File("youdao.exe");    accessFile = new RandomAccessFile(file, "rwd");    // 設定檔案的大小    accessFile.setLength(size);    // 每個線程下載的大小    blockSize = size / threadNum;    // 開三個線程 操作此檔案    for (int i = 1; i <= threadNum; i++) {     // 1 2 3     // 計算出每個線程開始的位置     int startSize = (i - 1) * blockSize;     // 結束位置     int endSize = (i) * blockSize;     // 當線程是最後一個線程的時候     if (i == threadNum) {      // 判斷檔案的大小是否大於計算出來的結束位置      if (size > endSize) {       // 結束位置 等於 檔案的大小       endSize = size;      }     }     // 為每個線程建立一個隨機的讀取     RandomAccessFile threadAccessFile = new RandomAccessFile(       file, "rwd");     new Thread(new DownLoadThread(i, threadAccessFile,       startSize, endSize, path)).start();    }   }  } catch (MalformedURLException e) {   // TODO Auto-generated catch block   e.printStackTrace();  } catch (IOException e) {   // TODO Auto-generated catch block   e.printStackTrace();  } } public static void main(String[] args) {  DownLoadTest downLoadTest = new DownLoadTest();  // 調用下載方法  downLoadTest.testDown(); }}class DownLoadThread implements Runnable { // 下載檔案的封裝 public RandomAccessFile accessFile; // 每個線程 都擁有一個accessFile的檔案對象 線程1 線程2 線程3 // 線程下載檔案的起始位置 public int startSize; public int endSize; // 檔案下載的path路徑 public String path; public int threadId; // 線程的標識 public DownLoadThread(int threadId, RandomAccessFile accessFile,   int startSize, int endSize, String path) {  this.threadId = threadId;  this.accessFile = accessFile;  this.startSize = startSize;  this.endSize = endSize;  this.path = path; } @Override public void run() {  // 執行run方法  try {   // 建立檔案   File threadFile = new File(threadId + ".txt");   if (threadFile.exists()) {    // 讀取該檔案的內容    // 建立檔案的輸入資料流對象    FileInputStream fis = new FileInputStream(threadFile);    // 採用工具類讀取    byte data[] = StreamTools.isToData(fis);    // 轉化成字串    String threadLen = new String(data);    if ((threadLen != null) && (!"".equals(threadLen))) {     startSize = Integer.valueOf(threadLen);     // 解決 416bug的錯誤     if (startSize > endSize) {      startSize = endSize - 1;     }    }   }   // 建立URL對象   URL url = new URL(path);   // 建立HttpURLConnection對象   HttpURLConnection httpURLConnection = (HttpURLConnection) url     .openConnection();   // 佈建要求的頭   httpURLConnection.setRequestMethod("GET");   // 佈建要求是否逾時時間   httpURLConnection.setConnectTimeout(5000);   // 設定   httpURLConnection     .setRequestProperty("User-Agent",       " Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)");   // 關鍵的設定   httpURLConnection.setRequestProperty("Range", "bytes=" + startSize     + "-" + endSize);   // 輸出當前線程   System.out.println("當前線程" + threadId + " 下載開始位置:" + startSize     + " 下載結束位置:" + endSize);   // 響應成功   // 設定隨機讀取檔案的 開始位置   accessFile.seek(startSize);   // 擷取相應流對象   InputStream is = httpURLConnection.getInputStream();   // 建立輸出資料流對象   byte buffer[] = new byte[1024];   int len = 0;   int threadTotal = 0;// 每個線程下載後儲存記錄 /   while ((len = is.read(buffer)) != -1) {    accessFile.write(buffer, 0, len);    threadTotal += len;// 記錄你寫入的長度 //xml檔案    // 通過檔案記錄檔案下載的長度    FileOutputStream fos = new FileOutputStream(threadFile);    fos.write((threadTotal + "").getBytes());    fos.flush();    fos.close();   }   accessFile.close();   is.close();   System.out.println(threadId + "線程執行完畢");   //線程操作   synchronized (DownLoadTest.class) {    DownLoadTest.threadCount++;    if (DownLoadTest.threadCount >= DownLoadTest.threadNum) {     for(int i=1;i<=DownLoadTest.threadNum;i++){      File file = new File(i+".txt");      if(file.exists()){       file.delete();      }     }    }   }  } catch (MalformedURLException e) {   // TODO Auto-generated catch block   e.printStackTrace();  } catch (IOException e) {   // TODO Auto-generated catch block   e.printStackTrace();  } }}

2.流工具的封裝 StreamTools.java

package www.csdn.net.down;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;public class StreamTools { public static byte[] isToData(InputStream is) throws IOException{  // 位元組輸出資料流  ByteArrayOutputStream bops = new ByteArrayOutputStream();  // 讀取資料的緩衝區  byte buffer[] = new byte[1024];  // 讀取長度的記錄  int len = 0;  // 迴圈讀取  while ((len = is.read(buffer)) != -1) {   bops.write(buffer, 0, len);  }  // 把讀取的內容轉換成byte數組  byte data[] = bops.toByteArray();  bops.flush();  bops.close();  is.close();  return data; }}

希望本文所述對大家Java程式設計有所協助。

聯繫我們

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