当前位置:首页 » JAVA技术教程

java多线程下载

2012-03-13 19:20 本站整理 浏览(22)

import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.IOException;
 import java.io.RandomAccessFile;
 import java.net.URL;
 import java.net.URLConnection;
 
 public class DLRunnable implements Runnable {
     static final int BUF_SIZE = 1024;
     URL url = Task.url;
     File file = Task.file;
     long pStart, pEnd, pCur, readLen = 0;
     int id, isDone = 0, isResume = 0;
 
     public DLRunnable(int id, long start, long end) {
         this.pStart = start;
         this.pEnd = end;
         this.id = id;
         this.pCur = this.pStart;
     }
 
     public void run() {
         try {
             url = new URL("http://dl_dir.qq.com/qqfile/qq/QQ2011/QQ2011.exe");
             URLConnection conn =  url.openConnection();
             conn.setAllowUserInteraction(true);
             BufferedInputStream bins = new BufferedInputStream(
                     conn.getInputStream());
             RandomAccessFile fos = null;
             if (isResume == 0) {
                 conn.setRequestProperty("Range", "bytes=" + pStart + "-" + pEnd);
                 fos = new RandomAccessFile(file, "rw");
                 fos.seek(pStart);
                 System.out.println("线程" + id + "开始下载...");
                 pCur = pStart;
             } else {
                 conn.setRequestProperty("Range", "bytes=" + pCur + "-" + pEnd);
                 fos = new RandomAccessFile(file, "rw");
                 fos.seek(pCur);
                 System.out.println("线程" + id + "继续开始下载...");
             }
             long startTime = System.currentTimeMillis();
             while (pCur < pEnd) {
                 byte buf[] = new byte[BUF_SIZE];
                 int len = bins.read(buf, 0, BUF_SIZE);
                 if (len == -1)
                     break;
                 fos.write(buf, 0, len);
                 pCur += len;
                 if (pCur > pEnd) {
                     readLen += (pEnd - (pCur - len) + 1);
                 } else {
                     readLen += len;
                 }
             }
             long totalTime = System.currentTimeMillis() - startTime;
             isDone = 1;
             System.out.println("线程" + id + "下载完毕!大小" + readLen + "字节"
                     + totalTime + "ms");
             bins.close();
             fos.close();
             Task.runnableArray.remove(this);
             Task.threadArray.remove(Task.threadArray.get(id-1));
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 }
实现runnable接口

import java.io.File;
 import java.io.IOException;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.net.URLConnection;
 import java.util.ArrayList;
 
 public class Task {
     static int THREAD_NUM = 3;
     static ArrayList<Thread> threadArray = new ArrayList<Thread>();
     static ArrayList<DLRunnable> runnableArray = new ArrayList<DLRunnable>();
     static URL url = null;
     static File file = null;
     static long blockLen, totalLen, startTime, totalTime;
 
     private void initTask() {
         try {
             url = new URL("http://dl_dir.qq.com/qqfile/qq/QQ2011/QQ2011.exe");
             file = new File("D:\\Users\\Meng\\Downloads\\QQ2011.exe");
             URLConnection conn = url.openConnection();
             long totalLen = conn.getContentLength();
             System.out.println("文件总大小:" + totalLen + "字节");
             if (totalLen == -1)
                 return;
             blockLen = (long) Math.ceil((double) totalLen / THREAD_NUM);
             System.out.println("每块长度:" + blockLen + "字节");
         } catch (MalformedURLException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
 
     private void startTask() {
         System.out.println("开始下载...");
         startTime = System.currentTimeMillis();
         for (int i = 0; i < THREAD_NUM; i++) {
             DLRunnable dlr = new DLRunnable(i + 1, blockLen * i, blockLen
                     * (i + 1));
             runnableArray.add(dlr);
             Thread dlt = new Thread(dlr);
             threadArray.add(dlt);
             dlt.start();
         }
     }
 
     private void stopTask(){ 
     System.out.println("下载中断...");
         for (Thread dlt : threadArray) {
             threadArray.remove(dlt);
             dlt = null;
         }
     }
 
     private void resumeTask() {
         System.out.println("继续下载...");
         for (DLRunnable dlr : runnableArray) {
             dlr.isResume=1;
             Thread dlt = new Thread(dlr);
             threadArray.add(dlt);
             dlt.start();
         }
     }
 
     public static void main(String[] args) throws InterruptedException {
         Task task = new Task();
         task.initTask();
         task.startTask();
         new Thread() {
             public void run() {
                 while (true) {
                     if (runnableArray.isEmpty()&&threadArray.isEmpty()) {
                         totalTime = System.currentTimeMillis() - startTime;
                         System.out.println("下载总用时:" + totalTime + "ms,平均速度:"
                                 + totalLen / totalTime + "kb/s");
                         break;
                     }
                 }
             }
         }.start();
         Thread.sleep(10000);
         task.stopTask();
         Thread.sleep(5000);
         task.resumeTask();
     }
 }
task类