<dependency> <groupId>org.jcommon.concurrent</groupId> <artifactId>jcommon-concurrent</artifactId> <version>1.3.1</version> </dependency> import org.jcommon.concurrent.ThreadUtils; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.concurrent.ExecutorService; public class FileDownloader implements Runnable { private String fileUrl; private String destinationPath; public FileDownloader(String fileUrl, String destinationPath) { this.fileUrl = fileUrl; this.destinationPath = destinationPath; } @Override public void run() { try { URL url = new URL(fileUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); FileOutputStream outputStream = new FileOutputStream(destinationPath); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = bufferedInputStream.read(buffer, 0, 1024)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); bufferedInputStream.close(); inputStream.close(); System.out.println("File downloaded: " + destinationPath); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { ExecutorService threadPool = ThreadUtils.currentThreadPool(); threadPool.execute(new FileDownloader("http://example.com/file1.txt", "path/to/save/file1.txt")); threadPool.execute(new FileDownloader("http://example.com/file2.txt", "path/to/save/file2.txt")); threadPool.execute(new FileDownloader("http://example.com/file3.txt", "path/to/save/file3.txt")); threadPool.shutdown(); } }


上一篇:
下一篇:
切换中文