private static Integer counts = 10; private Lock lock = new ReentrantLock(); public void start(){ List<Integer> list = new ArrayList<>(); list.add(1);list.add(2);list.add(3);list.add(4);list.add(5); list.forEach(t ->{ //handler task lam(t); }); }; void lam(Integer t) { List<Integer> list = new ArrayList(); int time = 60* AppContants.SLEEP_MINUTE; int count = time/(AppContants.SLEEP_MILLIS); if(!false){ ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); // System.err.println("线程开始-------->当前的系统时间为:" + sdf.format(new Date())); service.scheduleAtFixedRate( () -> { // System.out.println("第"+Integer.valueOf(list.size()+1)+"次执行,当前的系统时间为:" + sdf.format(new Date())); lock.lock();//首先lock()方法是平常使用得最多的一个方法,就是用来获取锁。如果锁已被其他线程获取,则进行等待。 try { counts=counts-1; list.add(1); if (list.size() >= 1) { service.shutdown(); // System.err.println("线程停止-------->当前的系统时间为:" + sdf.format(new Date())); lam2(counts); } }catch (Exception e){ }finally { lock.unlock();//释放锁 } }, 0, AppContants.SLEEP_MILLIS, TimeUnit.SECONDS); } } static void lam2(Integer counts) { System.out.println(counts); }
console:
9
8
7
6
5