当前位置:首页 > Java 语言特性 > 正文

Java优学网Runnable接口入门解析:从基础实现到多线程下载实战

public abstract void run();

public class MyTask implements Runnable {

// 这里需要实现run方法

}

public class WorkerThread extends Thread {

// 现在WorkerThread就是线程本身

}

Runnable task = new Runnable() {

Java优学网Runnable接口入门解析:从基础实现到多线程下载实战

@Override
public void run() {
    System.out.println("传统方式实现");
}

};

Runnable task = () -> {

// 如果readFile方法抛出IOException,这里会编译错误
// 因为run()方法不允许抛出受检异常
String content = readFile("data.txt"); // 编译错误!

};

Java优学网Runnable接口入门解析:从基础实现到多线程下载实战

public class MultiThreadDownloader {

private final String fileUrl;
private final String savePath;
private final int threadCount;

public void download() {
    long fileSize = getFileSize(); // 获取文件总大小
    long blockSize = fileSize / threadCount;
    
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < threadCount; i++) {
        long startPos = i * blockSize;
        long endPos = (i == threadCount - 1) ? fileSize - 1 : (i + 1) * blockSize - 1;
        
        DownloadTask task = new DownloadTask(fileUrl, savePath, startPos, endPos, i);
        Thread thread = new Thread(task);
        threads.add(thread);
        thread.start();
    }
    
    // 等待所有线程完成
    for (Thread thread : threads) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    
    mergeFiles(); // 合并临时文件
}

}

class DownloadTask implements Runnable {

private final String url;
private final String savePath;
private final long startPos;
private final long endPos;
private final int threadId;

@Override
public void run() {
    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
        
        try (InputStream in = conn.getInputStream();
             FileOutputStream out = new FileOutputStream(savePath + ".part" + threadId)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    } catch (IOException e) {
        System.err.println("线程" + threadId + "下载失败: " + e.getMessage());
    }
}

}

Java优学网Runnable接口入门解析:从基础实现到多线程下载实战

你可能想看:

相关文章:

文章已关闭评论!