CountDownLatch CyclicBarrier Semaphore

CountDownLatch

让一些线程阻塞直到另一些线程执行完成,有两个方法,一个是countDown(),一个是await(),调用countDown的线程不会被阻塞,调用await的线程才会被阻塞。countDown方法将计数器减一,只有当计数器为0时,调用await的线程才会被执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class CountLatchTest {
CountDownLatch count = new CountDownLatch(5);
public void test() {
System.out.println(Thread.currentThread().getName()+"\t 门栓减一");
count.countDown();
System.out.println(Thread.currentThread().getName()+"\t 还剩"+count.getCount());
}
public static void main(String[] args) throws InterruptedException {
CountLatchTest ct = new CountLatchTest();
// 线程数量如果小于5,调用await的线程将一直阻塞
for(int i=0;i<5;i++) {
new Thread(()->{
ct.test();
}).start();
}
Thread.sleep(1000);
ct.count.await();
System.out.println("main "+"\t 还剩"+ct.count.getCount());
}
}

CyclicBarrier

让一些线程到达一个屏障(同步点)直到所有的线程都到达,屏障才会打开,所有线程才开始执行,调用await方法将线程到达屏障。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class CycliBarrierDemo {

CyclicBarrier cyclic = new CyclicBarrier(5,()->{
System.out.println("所有线程都到了,我可以开始运行了");
});

public void test() throws InterruptedException, BrokenBarrierException{
System.out.println(Thread.currentThread()+"运行");
cyclic.await();
System.out.println("================");
}

public static void main(String[] args) throws InterruptedException {
CycliBarrierDemo ct = new CycliBarrierDemo();
// 如果运行的线程个数小于5,CyclicBarrier中的线程不会运行
for(int i=0;i<5;i++) {
new Thread(()->{
try {
Thread.sleep(1000);
ct.test();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}

###  Symaphore

用于多个共享资源的并发使用和并发线程数的控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SemaphoreDemo {

public static void main(String[] args) {
// 用于多个共享资源的并发使用和并发线程数的控制
Semaphore sem = new Semaphore(3);
// 6个线程争抢3个资源
for(int i=0;i<6;i++) {
new Thread(()->{
try {
sem.acquire();
System.out.println(Thread.currentThread().getName()+"\t获取资源");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName()+"\t获取资源三秒后离开");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
sem.release();
}
}).start();
}
}
}
文章目录
  1. 1. CountDownLatch
  2. 2. CyclicBarrier
|
载入天数...载入时分秒...