最近面试被问到一个题目:编写一个程序,开启 3 个线程,这三个线程分别负责打印 A、B、C,要求循环输出10次ABC,且输出的结果必须按顺序显示。如:ABCABCABC……

使用ReentrantLock实现

参考文章:https://my.oschina.net/beauxie/blog/1529954

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
public class TestThreadDemo  {
// 通过JDK5中的锁来保证线程的访问的互斥
private static Lock lock = new ReentrantLock();

private static int state = 0;// 用state来判断轮到谁执行

private static final int RUN_NUMBER=10;//表示循环的次数

//A线程
static class ThreadA extends Thread {

@Override
public void run() {
for (int i = 0; i < RUN_NUMBER;) {
lock.lock();//获取锁定
if (state % 3 == 0) {
System.out.print("A");
state++;
i++;
}
lock.unlock();//释放锁定,不释放锁定,会被该线程一直保持
}
}
}
//B线程
static class ThreadB extends Thread {

@Override
public void run() {
for (int i = 0; i < RUN_NUMBER;) {
lock.lock();
if (state % 3 ==1) {
System.out.print("B");
state++;
i++;
}
lock.unlock();
}
}
}
//C线程
static class ThreadC extends Thread {

@Override
public void run() {
for (int i = 0; i < RUN_NUMBER;) {
lock.lock();
if (state % 3 == 2) {
System.out.print("C");
state++;
i++;
}
lock.unlock();
}
}
}
public static void main (String[] args){
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}

使用synchronized实现

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
public class TestThreadDemo2 {
// 用于判断该输出那个字符 0输出A 1 输出B 2 输出C
private volatile int flag = 0;

public synchronized void printA() {
for (int i = 0; i < 10; i++) {
while (flag != 0){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("A");
flag = 1;
notifyAll();
}
}

/**
* 输出B方法
*/
public synchronized void printB(){
for (int i = 0; i < 10; i++) {
while (flag != 1){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("B");
flag = 2;
notifyAll();
}
}
public synchronized void printC() {
for (int i = 0; i < 10; i++) {
while (flag != 2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("C");
flag = 0;
notifyAll();
}

}

public static void main(String[] args) {
final TestThreadDemo2 demo = new TestThreadDemo2();
synchronized (demo){
new Thread(()->demo.printA()).start();
new Thread(()->demo.printB()).start();
new Thread(()->demo.printC()).start();
}
}
}