多线程循环打印代码
# 多线程循环打印数字
# 使用信号量Semaphore
public class CirclePrint {
public static void main(String[] args) {
int threadCount = 10;
int numCount = 100;
List<Semaphore> list = new ArrayList<>();
for (int i = 0; i < threadCount; i++) {
list.add(new Semaphore(0));
}
list.get(0).release();
for (int i = 0; i < threadCount; i++) {
int curIndex = i; // lambda 表达式引用的本地变量必须是最终变量或实际上的最终变量
Thread t = new Thread(() -> {
for (int j = curIndex; j < numCount; j+=threadCount) {
try {
list.get(curIndex).acquire();
System.out.println(Thread.currentThread().getName() + ": " + j);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
list.get((curIndex + 1) % threadCount).release();
}
}
});
t.start();
}
}
}
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
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
# 使用信号量Semaphore并使用一个类作为缓存
public class CirclePrint3 {
public static void main(String[] args) {
DataCache dataCache = new DataCache();
final int threadCount = 10;
final int numCount = 103;
List<Semaphore> list = new ArrayList<>(threadCount);
for (int i = 0; i < threadCount; i++) {
list.add(new Semaphore(0));
}
list.get(0).release();
for (int i = 0; i < threadCount; i++) {
int index = i; // lambda 表达式引用的本地变量必须是最终变量或实际上的最终变量
new Thread(() -> {
while (true) {
try {
list.get(index).acquire();
if (dataCache.get() < numCount) {
System.out.print(Thread.currentThread().getName() + ": ");
dataCache.add();
System.out.println(dataCache.get());
} else {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
list.get((index + 1) % threadCount).release();
}
}
}, String.valueOf(i)).start();
}
}
}
class DataCache {
private volatile int i = 0;
public void add() {
i++;
}
public int get() {
return i;
}
}
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
42
43
44
45
46
47
48
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
42
43
44
45
46
47
48
编辑 (opens new window)
上次更新: 2023/08/20, 21:21:52