-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
41 lines (36 loc) · 1.37 KB
/
Copy pathMain.java
File metadata and controls
41 lines (36 loc) · 1.37 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
// 1:无需package
// 2: 类名必须Main, 不可修改
/**
* 【示例代码】CountDownLatch 并发演示(非算法题)
* 用途:启动地图、音效、UI 三个资源加载线程,主线程通过 CountDownLatch.await() 等待三者全部完成后继续执行。
*/
public class Main {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(3); // 需要等待 3 个任务
// 资源加载任务
Runnable loadTask = () -> {
try {
Thread.sleep((long) (Math.random() * 2000));
System.out.println(Thread.currentThread().getName() + " 加载完成");
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
// 启动 3 个资源加载线程
new Thread(loadTask, "地图").start();
new Thread(loadTask, "音效").start();
new Thread(loadTask, "UI").start();
// 主线程等待所有资源加载完成
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("所有资源加载完成,开始游戏!");
}
}