线程池实践: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());
}
}
}
执行结果:


浙公网安备 33010602011771号