只有代码实现,具体基础知识请查看下面的博客(线程池+信号量)
https://blog.youkuaiyun.com/qq_33581278/article/details/84568675
https://blog.youkuaiyun.com/qq_33581278/article/details/84579454
1、自定义线程池
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class RecordDownloadExecutorPool
{
private static final Logger logger = LogManager.getLogger(RecordDownloadExecutorPool.class);
private RecordDownloadExecutorPool() {
logger.info("JdbcExecutorPool created!");
}
private static class SingletonHolder {
private static ExecutorService instance = new ThreadPoolExecutor(
1000,
2000,
20,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(1),
new ThreadPoolExecutor.AbortPolicy()
);
}
public static ExecutorService getInstance() {
return SingletonHolder.instance;
}
}
2、自定义控制线程池内运行线程数量类:bound为线程数量
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;
public class MtCallPeakBoundedExecutor {
private final ExecutorService executor;
private final Semaphore semaphore;
public MtCallPeakBoundedExecutor(ExecutorService executor, int bound) {
this.executor = executor;
this.semaphore = new Semaphore(bound);
}
public Semaphore getSemaphore() {
return semaphore;
}
public void submitTask(final Runnable command) {
try {
semaphore.acquire();
executor.execute(new Runnable() {
@Override
public void run() {
try {
command.run();
}finally {
semaphore.release();
}
}
});
} catch (InterruptedException e) {
semaphore.release();
}
}
}
3、自定义线程处理业务具体逻辑
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
public class DFTXRecordDownloadRunable implements Runnable {
private static final Logger logger = LogManager.getLogger(DFTXRecordDownloadRunable.class);
private String callId;
private String fileName;
public DFTXRecordDownloadRunable(String callId,String fileName) {
super();
this.callId = callId;
this.fileName = fileName;
}
@Override
public void run() {
//具体处理业务逻辑
}
}
4、如何使用
- 初始化控制线程类,100为运行的线程数量,具体可以自己定义
MtCallPeakBoundedExecutor mtCallPeakBoundedExecutor = new MtCallPeakBoundedExecutor(RecordDownloadExecutorPool.getInstance(), 100); - 初始化线程处理业务类
DFTXRecordDownloadRunable dftxRecordDownloadRunable = new DFTXRecordDownloadRunable(callId, fileName); - 处理业务类提交给线程池进行处理业务
dtmtCallPeakBoundedExecutor.submitTask(dftxRecordDownloadRunable);