JavaSE-多线程下载

package top.mengmei219;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownLoad {
    
    static int threadCound = 3; //线程数
    static int size; //每个线程分的大小
    static int finishThread = 0; //活动的线程数

    //多线程断点续传 下载
    public static void main(String[] args) {
        try {
            URL url = new URL("http://192.168.1.104:8080/itheima74/lczd.pdf");
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            int contentLength = urlConnection.getContentLength();
            
            RandomAccessFile random = new RandomAccessFile("/Users/mengmei/Desktop/lang.pdf", "rw");
            random.setLength(contentLength);
            
            for(int threadID=0; threadID 0 ) {
                        random.write(buffer, 0, len);
                        
                        lastPosition = lastPosition + len;
                        FileOutputStream tempOut = new FileOutputStream(tempFile);
                        tempOut.write(String.valueOf(lastPosition).getBytes());
                        tempOut.flush();
                        tempOut.close();
                    }
                    inputStream.close();
                    random.close();
                }
                
                
                synchronized (MyThread.class) {
                    System.out.println(threadID+" - 下载完成!");
                    finishThread ++;
                    
                    if (finishThread == threadCound) {
                        System.out.println("全部下载完成,删掉临时文件!");
                        for(int i=0; i

你可能感兴趣的:(JavaSE-多线程下载)