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); } }); }
原文:https://www.cnblogs.com/bevis-byf/p/14308237.html