forked from algorithm024/algorithm024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestM.java
More file actions
44 lines (37 loc) · 1.21 KB
/
TestM.java
File metadata and controls
44 lines (37 loc) · 1.21 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
42
43
44
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author JackWu
* @version 1.0
*/
public class TestM {
public static void main(String[] args) {
Semaphore semaphoreA = new Semaphore(1);
Semaphore semaphoreB = new Semaphore(0);
AtomicInteger num = new AtomicInteger(0);
new Thread(() -> {
try {
while (true) {
semaphoreA.acquire();
System.out.println(Thread.currentThread().getName() + ":" + num.getAndAdd(1));
semaphoreB.release();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"A").start();
new Thread(() -> {
try {
while (true) {
semaphoreB.acquire();
System.out.println(Thread.currentThread().getName() + ":" + num.getAndAdd(1));
semaphoreA.release();
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
},"B").start();
}
}