用三个线程按顺序循环打印 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
package test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
Test t = new Test();
ExecutorService es = Executors.newCachedThreadPool();
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
Lock lock = t.new Lock(list);
lock.list.forEach(e -> es.execute(t.new MyPrint(lock, e, 100)));
es.shutdown();
}
class Lock {
List<String> list;
String str;
Lock(List<String> list) {
this.list = list;
this.str = list.get(0);
}
}
class MyPrint implements Runnable {
String str;
Lock lock;
int loopNum;
final int num;
MyPrint(Lock lock, String str, int loopNum) {
this.lock = lock;
this.str = str;
this.loopNum = loopNum;
num = lock.list.indexOf(str);
}
@Override
public void () {
synchronized (lock) {
while (true) {
if (lock.str.equals(str)) {
System.out.println(str);
lock.str = (num + 1 == lock.list.size() ? lock.list.get(0) : lock.list.get(num + 1));
lock.notifyAll();
if (loopNum-- == 0)
break;
} else {
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}