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();
		}

	}

}

你可能感兴趣的:(java,SE)