MultiThreadDownLoad多线程下载

前言:

两种创建线程的方式:

第一种方式:使用Runnable接口创建线程。

第二种方式:直接继承Thread类创建对象。

     直接继承Thread类创建对象:(1)定义线程类(2)创建线程类对象(3)启动线程: 线程类对象.start();

用Runnanble 创建线程的步骤:1.定义一个Runnable接口类。2.在此接口类中定义一个对象作为参数run()方法。3.在run()方法中定义线程的操作。4.在其它类的方法中创建此Runnable接口类的实例对象,并以此实例对象作为参数创建线程类对象。5.用start()类方法启动线程。

MultiThreadDownLoad多线程下载:代码实现

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity {
	//通过tomact设置一个文件下载路径
    String path="http://172.28.21.32:8080/psiphon3.exe";
    int finishThread=0;
    //设置下载线程个数
    int threadcount=3;
    private ProgressBar pb;
    private TextView tv;
    //下载进度
    int downloadprogress=0;
    Handler handler=new Handler(){
    	public void handleMessage(android.os.Message msg) {
    		//通过设置文本显示下载进程
    		tv.setText((long)pb.getProgress()*100/pb.getMax()+"%");
    	};
    };
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pb=(ProgressBar) findViewById(R.id.progressBar);
		tv=(TextView) findViewById(R.id.textView1);
	}
	public void click(View v){
		Thread t=new Thread(){
			public void run(){
		try {
			URL url =new URL(path);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			//设置属性
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(8000);
			conn.setReadTimeout(8000);
			if(conn.getResponseCode()==200){
				//获取文件长度,便于分区间下载
				int length=conn.getContentLength();
				File file =new File(Environment.getExternalStorageDirectory(),getNameFromPath(path));
				RandomAccessFile raf=new RandomAccessFile(file, "rwd");
				raf.setLength(length);
				pb.setMax(length);
				raf.close();
				//计算线程区间
				int size=length/threadcount;
				for(int id=0;id<threadcount;id++){
					int startindex=id*size;
					int endindex=(id+1)*size-1;
					if(id==threadcount-1){
						endindex=length-1;
					}
					System.out.println("线程"+id+"下载了"+startindex+" ~ "+endindex);
					//创建一个下载线程
					new DownLoadThread(id,startindex,endindex).start();
				}

					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		};
		t.start();
	}
 static String getNameFromPath(String path) {
        int index=path.lastIndexOf("/");
		return path.substring(index+1);
	}
class DownLoadThread extends Thread{
	int ThreadID;
	int startindex;
	int endindex;
	public DownLoadThread(int threadID, int startindex, int endindex) {
		super();
		ThreadID = threadID;
		this.startindex = startindex;
		this.endindex = endindex;
	}
	public void run(){
		try {
			//创建临时文件记录
			File fileprogress=new File(Environment.getExternalStorageDirectory(),ThreadID+".txt");
			//定义上次读取的位置
			int lastprogress=0;
			if(fileprogress.exists()){
				FileInputStream fis=new FileInputStream(fileprogress);
				//使用缓冲区读取
				BufferedReader br=new BufferedReader(new InputStreamReader(fis));
				//得到上次进度
				lastprogress=Integer.parseInt(br.readLine());
				startindex+=lastprogress;
				fis.close();
				//把上一次下载进度加到进度条进度中
				downloadprogress += lastprogress;
				pb.setProgress(downloadprogress);
				//发送消息,让文本进度条改变
				handler.sendEmptyMessage(1);
			}
			//发送http请求,下载数据
			URL url=new URL(path);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(8000);
			conn.setReadTimeout(8000);
			//设置请求的数据区间
			conn.setRequestProperty("Range", "bytes="+startindex+"-"+endindex);
			if(conn.getResponseCode()==206){
				InputStream is=conn.getInputStream();
				File file=new File(Environment.getExternalStorageDirectory(),getNameFromPath(path));
				RandomAccessFile raf=new RandomAccessFile(file, "rwd");
				byte[] b=new byte[1024];
				int len=0;
				//记录下载进度
				//int total=0;
				//记录下载总进度
				int total=lastprogress;
				//设置写入的开始位置
				raf.seek(startindex);
				//while循环下载写入文件
				while((len=is.read(b))!=-1){
					raf.write(b,0,len);
					total+=len;
					System.out.println("线程" + ThreadID + "下载了:" + total);
					//创建一个进度临时文件,保存下载进度
					RandomAccessFile rafprogress=new RandomAccessFile(fileprogress, "rwd");
						rafprogress.write((total + "").getBytes());
						rafprogress.close();
						//每次下载len个长度的字节,马上把len加到下载进度中,让进度条能反应这len个长度的下载进度
						downloadprogress += len;
						pb.setProgress(downloadprogress);
						//发送消息,让文本进度条改变
						handler.sendEmptyMessage(1);
					}
					raf.close();
					System.out.println("线程" + ThreadID + "下载完毕" + "--------");
					finishThread++;
					synchronized (path) {
						if (finishThread == threadcount) {
							for (int i = 0; i < threadcount; i++) {
								File f = new File(Environment.getExternalStorageDirectory(),i + ".txt");
								f.delete();
							}
							finishThread = 0;
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}

注意权限:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值