//子线程循环2次,主线程5,接着子又循环2次,主循环5,如此循环20次.
public class Four {
public static void main(String[] args) {
final Business bbb = new Business();
new Thread(new Runnable(){
@Override
public void run() {
for(int i=1;i<=20;i++){
bbb.getSub(i);
}
}
}).start();
for(int i=1;i<=20;i++){
bbb.getMain(i);
}
}
}
class Business{
boolean flag = true; //true---sub
public synchronized void getSub(int xun){
if(flag){
//子线程循环2次
for(int i=1;i<=2;i++){
System.out.println("zi线程---总"+xun+"----小"+i);
}
flag = false;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void getMain(int xun){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
//主线程5
for(int i=1;i<=5;i++){
System.out.println("主线程---总"+xun+"----小"+i);
}
flag = true;
this.notify();
}
}
}
zi线程---总1----小1
zi线程---总1----小2
主线程---总2----小1
主线程---总2----小2
主线程---总2----小3
主线程---总2----小4
...