10個執行緒,累加一個數,加到1000後輸出
阿新 • • 發佈:2020-10-20
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 (; ; ) { int ret = a.get(); try { semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } 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(); } }