直接粘代码,如下:
package com.example.demo.test.threadPoolTest;
import com.example.demo.Entity.User;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* 本示例有一个疑点:多线程到底什么情况下不仅不会提高效率,反而导致代码的执行效率下降?
* runWithoutThread方法在单线程条件下向list集合添加10,000,000条数据,一般用时在8-9s左右,
* 但开启多线程之后,执行所用的时间反而增加为11-14s左右,这种情况目前还没有找到原因
*/
public class ThreadTest02 {
public static void main(String[] args) {
runWithThread();
runWithoutThread();
}
private static void runWithThread() {
ThreadPoolExecutor thisPool = new ThreadPoolExecutor(10, 20,
0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
ReentrantLock lock = new ReentrantLock();
List<User> list = new ArrayList<>(10000000);
Long startTime = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
thisPool.execute(() -> {
while (true) {
if (list.size() < 10000000) {
User user = new User(Thread.currentThread().getName() + String.valueOf(Math.random()));
lock.lock();
if (list.size() < 10000000) {
list.add(user);
}
lock.unlock();
} else {
break;
}
}
});
}
while (true) {
if (thisPool.getActiveCount() == 0) {
Long endTime = System.currentTimeMillis();
System.out.println("线程池并发运行用时" + (endTime - startTime));
// System.out.println(list.size());
break;
}
}
}
private static void runWithoutThread() {
Long startTime = System.currentTimeMillis();
List<User> list = new ArrayList<>(10000000);
while (true) {
if (list.size() < 10000000) {
User user = new User(Thread.currentThread().getName() + String.valueOf(Math.random()));
if (list.size() < 10000000) {
list.add(user);
}
} else {
break;
}
}
Long endTime = System.currentTimeMillis();
System.out.println("单线程运行用时" + (endTime - startTime));
}
}
运行结果:
线程池并发运行用时12924
单线程运行用时9583