Created
October 1, 2022 12:56
-
-
Save gcnyin/5149065058d38502dcb19952ea3cf389 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.nio.channels.Channels; | |
import java.nio.channels.ReadableByteChannel; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
public class TDownload { | |
public static void main(String[] args) throws InterruptedException { | |
Runnable task = () -> { | |
try { | |
File file = File.createTempFile("bili", "html"); | |
downloadFileFromURL("https://www.bilibili.com/", file); | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
}; | |
long start = System.currentTimeMillis(); | |
try (ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor()) { | |
for (int i = 0; i < 1000; i++) { | |
executorService.submit(task); | |
} | |
} | |
long end = System.currentTimeMillis(); | |
System.out.println(end - start); | |
} | |
private static void downloadFileFromURL(String urlString, File destination) throws IOException { | |
URL website = new URL(urlString); | |
ReadableByteChannel rbc = Channels.newChannel(website.openStream()); | |
FileOutputStream fos = new FileOutputStream(destination); | |
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); | |
fos.close(); | |
rbc.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
virtual thread对文件io没有用的