题目:交叉打印
1 public class OddThread{
2 private int i=1;
3 public synchronized void printOdd() {
4 while(i<100) {
5 if(i%2==0) {
6 try {
7 this.wait();
8 } catch (InterruptedException e) {
9 e.printStackTrace();
10 }
11 }
12 System.out.println(i);
13 i++;
14 this.notify();
15 }
16 }
17
18 public synchronized void printEvent() {
19 while(i<100) {
20 if(i%2==1) {
21 try {
22 this.wait();
23 } catch (InterruptedException e) {
24 e.printStackTrace();
25 }
26 }
27 System.out.println(i);
28 i++;
29 this.notify();
30 }
31 }
32
33
34 public static void main(String[] args) {
35 OddThread o = new OddThread();
36 new Thread(new Runnable() {
37 public void run() {
38 o.printOdd();
39
40 }
41 }).start();
42
43 new Thread(new Runnable() {
44 public void run() {
45 o.printEvent();
46
47 }
48 }).start();
49 }
50 }