public class TestCollection {
public static void main(String[] args) {
TestCollection test = new TestCollection();
test.t1();
test.t2();
}
public static Object obj = new Object();
public void t1() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (obj) {
try {
for (int i = 0; i < 26; i++) {
System.out.print(i);
obj.notifyAll();
obj.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
public void t2() {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (obj) {
try {
char a = 'A';
for (int i = 0; i < 26; i++) {
System.out.println((char) (a + i));
obj.notifyAll();
obj.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
}
运行结果:
0A
1B
2C
3D
4E
5F
6G
7H
8I
9J
10K
11L
12M
13N
14O
15P
16Q
17R
18S
19T
20U
21V
22W
23X
24Y
25Z
使用wait和notify,简单的例子。
wait和notify需要在synchronize中执行。