CountDownLatch(减法计数器)
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(7);
for (int i = 1; i <=7 ; i++) {
new Thread(
()->{
System.out.println(Thread.currentThread().getName()+"走了");
countDownLatch.countDown();
},String.valueOf(i)
).start();
}
countDownLatch.await();
System.out.println("结束");
}
}
CyclicBarrier (定数)
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("人员到齐");
});
for (int i = 1; i <= 7; i++) {
final int temp = i;
new Thread(
() -> {
System.out.println(Thread.currentThread().getName() + "报道" + temp + "号");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}
).start();
}
}
}
Semaphore
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <=6 ; i++) {
new Thread(
()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"停车");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"走开");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)
).start();
}
}
}