1.CountDownLatch
计数器减为0的时候开始后面的代码
CountDownLatch.countDown()
CountDownLatch.await()
package Demo;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//CountDownLatch计数器
//计数器归0的时候继续执行下面代码
CountDownLatch c1 = new CountDownLatch(6);
for(int i = 1;i <= 6;i++){
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "Go");
c1.countDown();
},String.valueOf(i)).start();
}
c1.await();
System.out.println("1");
}
}
2.CyclicBarrier
上面的是减这个是加
package Demo;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier c1 = new CyclicBarrier(7,()->{
System.out.println("ok");
});
for (int i = 0; i < 7; i++) {
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+ temp);
try {
c1.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
3.Semaphore
信号量
相当于一个坑位
package Demo;
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("ok");
TimeUnit.SECONDS.sleep(1);
System.out.println("run");
}catch (Exception e){
e.printStackTrace();
}finally {
semaphore.release();
}
}).start();
}
}
}