package thread; /**
* 需求:线程编程:子线程先运行 2 次,然后主线程运行 4 次,如此反复运行 3 次。
* @author zhongfg
* @date 2015-06-16
*/
class Business { // 控制由谁执行
boolean bShouldSub = true; public synchronized void MainThread(int i) {
if (bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 4; j++) {
System.out.println(Thread.currentThread().getName() + "-->i=" + i
+ ",j=" + j);
}
bShouldSub = true;
this.notify();
} public synchronized void SubThread(int i) {
if (!bShouldSub) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j < 2; j++) {
System.out.println(Thread.currentThread().getName() + "->i=" + i
+ ",j=" + j);
}
bShouldSub = false;
this.notify();
}
} public class ThreadInterview {
public static void main(String args[]) { ThreadInterview tp = new ThreadInterview();
tp.init();
} public void init() { final Business business = new Business();
new Thread(new Runnable() { public void run() {
for (int i = 0; i < 3; i++) {
// 调用子线程中的方法
business.SubThread(i);
}
}
}).start(); for (int i = 0; i < 3; i++) {
business.MainThread(i);
}
}
} 运行结果:
Thread-0->i=0,j=0
Thread-0->i=0,j=1
main-->i=0,j=0
main-->i=0,j=1
main-->i=0,j=2
main-->i=0,j=3
Thread-0->i=1,j=0
Thread-0->i=1,j=1
main-->i=1,j=0
main-->i=1,j=1
main-->i=1,j=2
main-->i=1,j=3
Thread-0->i=2,j=0
Thread-0->i=2,j=1
main-->i=2,j=0
main-->i=2,j=1
main-->i=2,j=2
main-->i=2,j=3