10个线程,累加一个数,加到1000后输出
public static void main(String[] args) { AtomicInteger a = new AtomicInteger(0); CountDownLatch countDownLatch = new CountDownLatch(1); Semaphore semaphore = new Semaphore(1); for (int i = 0; i < 10; i++) { Thread t1 = new Thread(() -> { for (; ; ) {try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); }
int ret=a.get(); if (ret == 1000) { countDownLatch.countDown(); break; } else { ret = a.incrementAndGet(); System.out.println(ret); } semaphore.release(); } }); t1.setDaemon(true); t1.start(); } try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }