多线程下载基础示例JAVA SE

13 篇文章 0 订阅
package com.dong.multhreaddownload;

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

public class TestMain {

	static int threadCont = 3;

	/**
	 * @param args
	 * @throws MalformedURLException
	 */
	public static void main(String[] args) throws Exception {
		// TOMCAT WEBAPP/ROOT中,存放一个EXE文件
		String path ="http://192.168.1.100:8080/cbox2.4.0.9.exe";
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");
		int code = conn.getResponseCode();
		if (200 == code) {
			int length = conn.getContentLength();
			System.out.println("file length is" + length);
			//创建一个文件
			RandomAccessFile raf = new RandomAccessFile("cbox2.4.0.9.exe", "rwd");
			raf.setLength(length);
			raf.close();
			// 平均每一个线程的大小
			int blockSize = length / threadCont;
			for (int threadId = 1; threadId <= threadCont; threadId++) {
				int startIndex = (threadId - 1) * blockSize;
				int endIndex = threadId * blockSize - 1;
				if (threadId == threadCont) {
					endIndex = length;
				}
				System.out.println("Thread :" + threadId + "下载" + startIndex
						+ "--->" + endIndex);
				new DownThread(threadId, startIndex, endIndex, path).start();
			}

		} else {
			System.out.println("server error");
		}

	}

	public static class DownThread extends Thread {

		private int ThreadId;
		
		private int startIndex,endIndex;
		
		private String path;
		
		public DownThread(int threadId, int startIndex, int endIndex,String path) {
			this.ThreadId = threadId;
			this.startIndex = startIndex;
			this.endIndex = endIndex;
			this.path = path;
		}



		public void run() {
			try {
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex);
				conn.setRequestMethod("GET");
				int code= conn.getResponseCode();//如果请求全部资源200代表OK,请求部分资源,206代表OK
				System.out.println("code is "+code);
				InputStream is = conn.getInputStream();
				RandomAccessFile raf = new RandomAccessFile("cbox2.4.0.9.exe", "rwd");
				raf.seek(startIndex);
				int len  = 0;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer))!=-1) {
					raf.write(buffer,0,len);
				}
				System.out.println("thread"+ThreadId+ "is downed");
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值