线程池实践:10个线程处理1000个下载请求

使用阻塞队列存储下载链接,使用固定数量线程池,通过实现Runnable接口提交下载任务#

public class Main {
	private static final int capacity=1000;
	private static BlockingQueue<String> storage=new LinkedBlockingQueue<>(capacity);
	static class Downloader implements Runnable {
		@Override
		public void run() {
			try {
				//模拟下载事件处理:
				System.out.println(Thread.currentThread().getName() + " downloads: " + storage.take());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args){
		//模拟下载链接准备:
		for(int i=0;i<capacity;i++){
			try {
				storage.put("https://mydrive.com/user/gigabit/storage/file"+(i+1)+".zip");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		//创建线程池:
		ThreadPoolExecutor downloaderPool=new ThreadPoolExecutor(
				10,//CorePoolSize
				10,//MaxPoolSize
				1,//KeepAliveTime
				TimeUnit.SECONDS,
				new LinkedBlockingQueue<Runnable>());
		//向线程池提交1000次下载任务:
		for(int i=0;i<capacity;i++){
			downloaderPool.execute(new Downloader());
		}
	}
}

执行结果:
image

posted @   吉比特  阅读(247)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
欢迎阅读『线程池实践:10个线程处理1000个下载请求』
点击右上角即可分享
微信分享提示
主题色彩