1 package thread;
2
3 /**
4 * 需求:线程编程:子线程先运行 2 次,然后主线程运行 4 次,如此反复运行 3 次。
5 * @author zhongfg
6 * @date 2015-06-16
7 */
8 class Business { // 控制由谁执行
9 boolean bShouldSub = true;
10
11 public synchronized void MainThread(int i) {
12 if (bShouldSub) {
13 try {
14 this.wait();
15 } catch (InterruptedException e) {
16 e.printStackTrace();
17 }
18 }
19 for (int j = 0; j < 4; j++) {
20 System.out.println(Thread.currentThread().getName() + "-->i=" + i
21 + ",j=" + j);
22 }
23 bShouldSub = true;
24 this.notify();
25 }
26
27 public synchronized void SubThread(int i) {
28 if (!bShouldSub) {
29 try {
30 this.wait();
31 } catch (InterruptedException e) {
32 e.printStackTrace();
33 }
34 }
35 for (int j = 0; j < 2; j++) {
36 System.out.println(Thread.currentThread().getName() + "->i=" + i
37 + ",j=" + j);
38 }
39 bShouldSub = false;
40 this.notify();
41 }
42 }
43
44 public class ThreadInterview {
45 public static void main(String args[]) {
46
47 ThreadInterview tp = new ThreadInterview();
48 tp.init();
49 }
50
51 public void init() {
52
53 final Business business = new Business();
54 new Thread(new Runnable() {
55
56 public void run() {
57 for (int i = 0; i < 3; i++) {
58 // 调用子线程中的方法
59 business.SubThread(i);
60 }
61 }
62 }).start();
63
64 for (int i = 0; i < 3; i++) {
65 business.MainThread(i);
66 }
67 }
68 }
69
70 运行结果:
71 Thread-0->i=0,j=0
72 Thread-0->i=0,j=1
73 main-->i=0,j=0
74 main-->i=0,j=1
75 main-->i=0,j=2
76 main-->i=0,j=3
77 Thread-0->i=1,j=0
78 Thread-0->i=1,j=1
79 main-->i=1,j=0
80 main-->i=1,j=1
81 main-->i=1,j=2
82 main-->i=1,j=3
83 Thread-0->i=2,j=0
84 Thread-0->i=2,j=1
85 main-->i=2,j=0
86 main-->i=2,j=1
87 main-->i=2,j=2
88 main-->i=2,j=3