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