代码先放在这里,分析后面会出~
import java.util.concurrent.Semaphore; public class ThreadDemo13 { public static void main(String[] args) { Semaphore semaphore = new Semaphore(2); Counter counter = new Counter(); Thread t1 = new Thread(() -> { try { semaphore.acquire(); for (int i = 0; i < 10000; i++) { counter.add(); } } catch (InterruptedException e) { throw new RuntimeException(e); } }); t1.start(); Thread t2 = new Thread(() -> { try { semaphore.acquire(); for (int i = 0; i < 10000; i++) { counter.add(); } } catch (InterruptedException e) { throw new RuntimeException(e); } }); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println(counter.count); } } class Counter { public int count = 0; public void add() { count++; } }