java定时器

 

public class HelloTimer {

	public static ConcurrentHashMap<String, Integer> task_map = new ConcurrentHashMap<String, Integer>();
	public static void main(String[] args) throws InterruptedException {
		task_map.put("task_1", 1);
		final CountDownLatch latch = new CountDownLatch(1);
		ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
		final ScheduledFuture<?> future = scheduler.scheduleAtFixedRate(new Runnable() {
			public void run() {
				System.out.println("time:"+System.currentTimeMillis());
				int i = task_map.get("task_1");
				System.out.println("aaaaaaaaaaaaaaaa"+i);
				i++;
				task_map.put("task_1", i);
			}
		}, 0,1, TimeUnit.SECONDS);
		scheduler.scheduleAtFixedRate(new Runnable() {
			public void run() {
				int i = task_map.get("task_1");
				System.out.println("bbbbbbbbbbbbbbbb");
				if (i==6) {
					future.cancel(true);
					latch.countDown();
				}
			}
		},0,1,TimeUnit.SECONDS);
//		scheduler.schedule(new Runnable() {
//			public void run() {
//				future.cancel(true);
//				latch.countDown();
//			}
//		},5,TimeUnit.SECONDS);
		latch.await();
		scheduler.shutdown();
		
	}
	
}

 

你可能感兴趣的:(java,CountDownLatch)