for循环太慢了,用线程池同步运行优化
- 第一种方法
public static void main(String[] args) {
long start = System.currentTimeMillis();
List list = new ArrayList();
for (int i = 0; i <1000000; i++) {
list.add(i);
}
//定义线程数量为20,可根据服务器配置适当调整大小
Thread(list, 20);
long end = System.currentTimeMillis();
System.out.println("总时间 = " + (end - start));
}
//此处有加锁
public synchronized static void Thread(List list, int nThread) {
if (list.size() == 0 || nThread <= 0 ) {
return;
}
Semaphore semaphore = new Semaphore(nThread);//定义几个许可
ExecutorService executorService = Executors.newFixedThreadPool(nThread);//创建一个固定的线程池
for (Object number : list) {
try {
semaphore.acquire();
executorService.execute(() -> {
System.out.println("number:" + number);
semaphore.release();
});
} catch (InterruptedException e) {
}
}
executorService.shutdown();
}
2.第二种方法
public static void main(String[] args) {
long start = System.currentTimeMillis();
List list = new ArrayList();
for (int i = 0; i <1000000; i++) {
list.add(i);
}
ExecutorService pool = Executors.newFixedThreadPool(10);
for (Object number : list){
Runnable runnable = new Runnable(){
@Override
public void run() {
System.out.println(number);
}
};
pool.execute(runnable);
}
pool.shutdown();
while(true){
if(pool.isTerminated()){
break;
}
}
long end = System.currentTimeMillis();
System.out.println("总时间 = " + (end - start) );
}
3.第三种方法,并行流
public static void main(String[] args) {
long start = System.currentTimeMillis();
List list = new ArrayList();
for (int i = 0; i <10; i++) {
list.add(i);
}
list.parallelStream().forEach(s->{
System.out.println(s);
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
});
long end = System.currentTimeMillis();
System.out.println("总时间 = " + (end - start));
}