java基礎代碼:多線程下載示例

作者的個人分享網:分享時刻【www.itison.cn】

java多線程下載示例

多線程下載,如果想要做測試,必須要修改相應的文件路徑,打開服務器纔可,否則會出現異常。
代碼如下:

/**多線程下載**/

package com.demo;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


class DownloadThread extends Thread {
	int start;
	int end;
	String path;
	
	public DownloadThread(int start, int end, String path) {
		this.start = start;
		this.end = end;
		this.path = path;
	}
	
	public void run() {
		try {
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Range", "bytes=" + start + "-" + end);
			InputStream is = conn.getInputStream();
			System.out.println(Thread.currentThread().getName() + "號線程負責的下載範圍:" + start + "---" + end);
			RandomAccessFile raf = new RandomAccessFile("c:\\aaa\\test.exe", "rw");
			raf.seek(start);
			
			byte[] b = new byte[1024];
			int nRead = 0;
			while((nRead = is.read(b)) != -1) {
				raf.write(b, 0, nRead);
			}
			
			System.out.println(Thread.currentThread().getName() + "號線程下載完畢!");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


public class MulThreadDownload {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			String path = "http://localhost:8080/MyWebServer/qqpcmgr.exe";
			URL url = new URL(path);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			int length = conn.getContentLength();
			
			System.out.println("資源總長度:" + length);
			
			RandomAccessFile raf = new RandomAccessFile("c:\\aaa\\test.exe", "rw");
			raf.setLength(length);
			
			int blockCount = 3;						//總的線程數量
			int blockSize = length / blockCount;	//每個線性要下載的數據量
			
			for (int i = 1; i <= blockCount; i++) {
				int start = (i - 1) * blockSize;
				int end = i * blockSize - 1;
				if (i == blockCount) {
					end = length - 1;
				}
				new DownloadThread(start, end, path).start();
			}
			
			raf.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

發佈了43 篇原創文章 · 獲贊 86 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章