1. countdownlatch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Main {
public static void main(String[] args) throws InterruptedException {
// 主线程等待n个子线程,每次调用countdown表示该线程准备好了
CountDownLatch latch = new CountDownLatch(2);
new Thread(() -> {
System.out.println("线程1执行");
latch.countDown();
}).start();
new Thread(() -> {
System.out.println("线程2执行");
latch.countDown();
}).start();
new Thread(() -> {
System.out.println("线程3执行");
latch.countDown();
}).start();
latch.await();
System.out.println("执行结束");
}
}
  1. cyclicbarrier
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
public class Main {
public static void main(String[] args) throws InterruptedException {
// 当n个线程同时到达时执行回调方法,await表示线程到达
CyclicBarrier cyc = new CyclicBarrier(2, () -> {
System.out.println("到齐啦");
});
new Thread(() -> {
try {
cyc.await();
System.out.println("线程1运行");
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}).start();
new Thread(() -> {
try {
cyc.await();
System.out.println("线程2运行");
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (BrokenBarrierException e) {
throw new RuntimeException(e);
}
}).start();
}
}
  1. semaphore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Main {
public static void main(String[] args) throws InterruptedException {
// 控制最多n个线程同时执行,acquire表示获取信号量,release是释放
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 10; i++) {
int ii = i;
new Thread(() -> {
try {
semaphore.acquire();
System.out.println("线程" + ii + "运行");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}).start();
}
}
}
  1. atomicinteger
1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static volatile AtomicInteger INTEGER = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
// 原子类实现自增操作
for (int i = 0; i < 10; i++) {
new Thread(INTEGER::incrementAndGet).start();
}
Thread.sleep(5);
System.out.println(INTEGER.get());
}
}