---
title: "java多线程下载"
author: "何先生"
date: "2013-08-08T14:58:09Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-08-08T14:58:09Z"
id: 1922041
url: "https://mrhe.iteye.com/blog/1922041"
---

![](http://dl2.iteye.com/upload/attachment/0087/9779/3c25b8cc-5897-36d9-b557-aebe83d819ca.jpg)

![](http://dl2.iteye.com/upload/attachment/0087/9781/9cdebead-6bcd-3c34-a447-0156274a9eec.jpg)

```java

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;


public class DownLoader {
	//多线程文件下载
	//使用HTTP的Range字段指定每条线程从文件的什么位置开始下载，如从文件的2mb位置下载就是bytes=2097252,2MB的字节
	public static void main(String[] args){
		//主方法
		DownLoader d=new DownLoader();
		try {
			d.download();
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void download() throws Throwable{
		String filename="QQGAME.exe";//取文件名
		//得到下载路径
		String path="http://dldir3.qq.com/minigamefile/QQGame2013Beta4P2_setup_guanjia.EXE";
		URL url=new URL(path);//建立url对象，把这个路径传进去
		HttpURLConnection conn=(HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5*1000);//设置超时
		conn.setRequestMethod("GET");//设置请求方式
		int filelength=conn.getContentLength();//获取下载文件长度
		System.out.println(filelength);
		
		//得到随机文件类   第一个参数是文件名称  第二个参数rw是可以对文件可以进行读和写的操作
		RandomAccessFile file=new RandomAccessFile(filename, "rw");
		file.setLength(filelength);//设置本地文件长度等于下载文件长度
		file.close(); //关闭这个文件
		conn.disconnect(); //先断掉这个链接，这个方法不调用也可以
		int threadsize=3;//线程数
		int threadlength = filelength%3==0 ? filelength/3:filelength/3+1;//每条线程的下载长度

		for (int i = 0; i < threadsize; i++) {
			//计算每条线程应该从文件的什么位置开始下载
			int startposition=i*threadlength;
			RandomAccessFile threadfile=new RandomAccessFile(filename,"rw");
			threadfile.seek(startposition);//从文件的什么位置开始写入数据
			//启动3条线程分别从startposition指定的位置下载文件
			new DownLoadThread(i, path, startposition, threadfile, threadlength).start();
			//让用户输入一个字符才决定它是否退出
//			int quit = System.in.read();
//			while('q'!=quit){
//				Thread.sleep(2*1000);
//			}
			
		}
		
	}
	private class DownLoadThread extends Thread{
		private int threadid;
		private int startposition;
		private RandomAccessFile threadfile;
		private int threadlength;
		private String path;
		
		public DownLoadThread(int threadid,String path,int startposition,RandomAccessFile threadfile
				,int threadlength){
			this.threadid = threadid;
			this.startposition = startposition;
			this.threadfile = threadfile;
			this.threadlength = threadlength;
			this.path=path;
		}

		@Override
		public void run() {
			try {
				//上一个与网络的连接已经关闭了，所以要再一次得到与服务器的连接
				URL url=new URL(path);
				HttpURLConnection conn=(HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5*1000);
				conn.setRequestMethod("GET");
				//指定从文件什么位置开始下载
				conn.setRequestProperty("Range", "bytes="+startposition+"-");
				
				InputStream instream=conn.getInputStream();
				
				byte[] buffer=new byte[1024];
				int len=-1;
				int length = 0;
				while(length<threadlength && (len=instream.read(buffer))!=1){
					threadfile.write(buffer,0,len);
					length += len; //累计下载长度
				}
				threadfile.close();
				instream.close();
				System.out.println("线程"+(threadid+1)+"已经下载完成");
				
				
				
			} catch (Exception e) {
				System.out.println("线程"+(threadid+1)+"已经下载出错");
			}
		}
		
		
	}
}


```