多线程并发防止资源争抢工具类 函数式编程
package cn.com.util; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; public class ConcurrentUtils { // 初始化公平锁 private static final ReentrantLock lock = new ReentrantLock(true); private static final Map<String, String> JOB_CONTEXT = new ConcurrentHashMap(); public static void run(TaskFunction function) throws Exception { if (lock.tryLock(3, TimeUnit.SECONDS)) { // 执行任务-适用于耗时较短的任务 try { function.run(); } catch (Exception e) { throw e; } finally { lock.unlock(); } } } /** * 适用于可以分类的任务并发执行 * @param jobCode 任务分类 * @param function * @throws Exception */ public static void run(String jobCode, TaskFunction function) throws Exception { if (lock.tryLock(3, TimeUnit.SECONDS)) { try { // 再次判断, 提高首次并发效率 if (!JOB_CONTEXT.containsKey(jobCode)) { JOB_CONTEXT.put(jobCode, Thread.currentThread().getName()); } else { return; } } finally { lock.unlock(); } // 执行任务-耗时较长-所以加锁加在上面-提高并发效率 try { function.run(); } catch (Exception e) { throw e; } finally { JOB_CONTEXT.remove(jobCode); } } } @FunctionalInterface public static interface TaskFunction { void run(); } }
使用示例:
for (String jobCode : jobCodeList) { // jobCode -- 任务分类标识 ConcurrentUtils.run(jobCode, () -> { try { // 本次的任务 this.job(); } catch (Exception e) { log.error("job run error!", e); } }); }
说明: 本次本丢弃的任务应该通过程序归入下次任务执行...... 结合CompletionService一起使用 地址: https://www.cnblogs.com/bevis-byf/p/11658643.html