import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TextExecutor {
public ExecutorService fixedExecutorService = Executors.newFixedThreadPool(5);
public ExecutorService cachedExecutorService = Executors.newCachedThreadPool();
public ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();
public void testExecutorException() {
for (int i = 0; i < 10; i ++) {
// 增加isShutdown()判断
if (!fixedExecutorService.isShutdown()) {
fixedExecutorService.execute(new SayHelloRunnable());
}
fixedExecutorService.shutdown();
}
}
private class SayHelloRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("hello world!");
}
}
}
public static void main(String[] args) {
TextExecutor testExecutor = new TextExecutor();
testExecutor.testExecutorException();
}
}
线程数量超过maximumPoolSize
示例代码里使用了自定义的ExecutorService,可以复现这种问题:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class TextExecutor {
public ExecutorService fixedExecutorService = Executors.newFixedThreadPool(5);
public ExecutorService cachedExecutorService = Executors.newCachedThreadPool();
public ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();
public ExecutorService customerExecutorService = new ThreadPoolExecutor(3, 5, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
public void testExecutorException() {
for (int i = 0; i < 10; i ++) {
// 增加isShutdown()判断
if (!fixedExecutorService.isShutdown()) {
fixedExecutorService.execute(new SayHelloRunnable());
}
fixedExecutorService.shutdown();
}
}
public void testCustomerExecutorException() {
for (int i = 0; i < 100; i ++) {
customerExecutorService.execute(new SayHelloRunnable());
}
}
private class SayHelloRunnable implements Runnable {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
System.out.println("hello world!");
}
}
}
public static void main(String[] args) {
TextExecutor testExecutor = new TextExecutor();
testExecutor.testCustomerExecutorException();;
}
}
解决方案
尽量调大maximumPoolSize,例如设置为Integer.MAX_VALUE
public ExecutorService customerExecutorService = new ThreadPoolExecutor(3, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
2.使用其他排队策略,例如LinkedBlockingQueue
public ExecutorService customerExecutorService = new ThreadPoolExecutor(3, 5, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());