面试题:三个线程循环打印ABC

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
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ABCPrinter implements Runnable{

private static int cnt=1;
private static Object lock=new Object();
private int num;


public ABCPrinter(int num){
this.num=num;
}

public void run(){
while(true){
synchronized(lock){
while(cnt%3!=num){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println((char)('A'+num));
cnt++;
lock.notifyAll();
}
}
}

/*
* await与notify
*/
static Lock lock2=new ReentrantLock();
static Condition[] conditions=new Condition[]{lock2.newCondition(), lock2.newCondition(), lock2.newCondition()};


static class Printer implements Runnable{
private int num;
private Condition[] conditions;

public Printer(int num, Condition[] conditions){
this.num=num;
this.conditions=conditions;
}


@Override
public void run() {
while(true){
lock2.lock();;
try{
while(cnt%3!=num){
try {
conditions[num].await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println((char)('A'+num));
cnt++;
conditions[cnt%3].signal();
}finally{
lock2.unlock();
}
}
}
}

public static void main(String[] args) {
// new Thread(new ABCPrinter(0)).start();
// new Thread(new ABCPrinter(1)).start();
// new Thread(new ABCPrinter(2)).start();
//方法二
new Thread(new Printer(0, conditions)).start();
new Thread(new Printer(1, conditions)).start();
new Thread(new Printer(2, conditions)).start();
}
}

这两种方法是自己想的,一个是用了wait-notify,第二种用了await-signal,主体思想都是一样的,构造线程的时候指定一个字母,让它只打印这个,再设置一个静态变量,不停的增长,然后每个线程都去检测,如果轮到自己了就打印,不是自己就继续等待,考察的就是线程间通信。