@SpringBootTest @Slf4j public class TestDo { @Resource private RedisUtil redisUtil; private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2); SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); @Test public void test() { List<Long> idList = new LinkedList<>(); for (int i = 0; i < 10; i++) { idList.add(Long.valueOf(i)); } for (Long shopId : idList) { if (null == shopId) { continue; } String redisLock = "test:demo:" + shopId; String value = redisUtil.get(redisLock, String.class); log.info("value:{}", value); if (Objects.equals(value, shopId.toString())) { continue; } redisUtil.set(redisLock, shopId.toString()); log.info("shopId:{}", shopId); scheduledExecutorService.execute(() -> { try { String threadName = Thread.currentThread().getName(); long threadId = Thread.currentThread().getId(); log.info("线程名称为threadName:{},线程id为threadId:{}",threadName,threadId); String startDate = formatter.format(new Date()); //模拟业务 try { //5秒 log.info("start==="); Thread.sleep(5000); } catch (InterruptedException e) { log.error("e:{}", e); } String endDate = formatter.format(new Date()); } catch (Exception e) { log.error("threadPool.execute:", e); } finally { //释放锁 redisUtil.deleteCache(redisLock); } }); } } }