多线程交替打印ABC

Java管程实现

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
49
50
51
52
53
54
55
56
57
58
59
class Solution {

static final Object lock = new Object();
static int state = 0;

public static void main(String[] args) {
Thread a = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (state % 3 != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("A");
state++;
lock.notifyAll();
}
}
});
Thread b = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (state % 3 != 1) {
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("B");
state++;
lock.notifyAll();
}
}
});
Thread c = new Thread(() -> {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (state % 3 != 2) {
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("C");
state++;
lock.notifyAll();
}
}
});
a.start();
b.start();
c.start();
}
}

ReentrantLock实现

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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class Solution {

static final ReentrantLock lock = new ReentrantLock();
static final Condition printA = lock.newCondition();
static final Condition printB = lock.newCondition();
static final Condition printC = lock.newCondition();
static int state = 0;

public static void main(String[] args) {
Thread a = new Thread(() -> {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (state % 3 != 0) {
printA.await();
}
System.out.println("A");
state++;
printB.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
});
Thread b = new Thread(() -> {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (state % 3 != 1) {
printB.await();
}
System.out.println("B");
state++;
printC.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
});
Thread c = new Thread(() -> {
for (int i = 0; i < 10; i++) {
lock.lock();
try {
while (state % 3 != 2) {
printC.await();
}
System.out.println("C");
state++;
printA.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
});
a.start();
b.start();
c.start();
}
}