MultiThreadDownLoad多线程下载

来源:互联网 发布:csi 软件 编辑:程序博客网 时间:2024/06/11 06:16

前言:

两种创建线程的方式:

第一种方式:使用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()+"%");    };    };@Overrideprotected 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();}}}}

注意权限:



原创粉丝点击