CountDownLatch
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo {
public static final int NUM = 6;
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(NUM);
for(int i = 1; i <= NUM; i++) {
new Thread(()-> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( Thread.currentThread().getName() + "員工下班");
latch.countDown();
}, String.valueOf(i)).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("管理員鎖門");
}
}
CyclicBarrier
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier barrier = new CyclicBarrier(7, ()-> {
System.out.println(Thread.currentThread().getName() + "召喚神龍");
});
for(int i = 1; i <= 7; i++) {
final int tmp = i;
new Thread(()-> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "收集到第" + tmp + "顆龍珠");
try {
barrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}, String.valueOf(i)).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 = 0; i < 6; i++) {
new Thread(()-> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "搶到車位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName() + "停3秒後離開");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
}, String.valueOf(i)).start();
}
}
}