创建子父线程,保证子线程执行5次后,父线程执行3次 如此循环10次!
public class Test {
private boolean subFlag=true;//判断是主线程还是子线程 如果为true为子线程 false为主线程
public synchronized void sub(int loop){
// 如果子线程不可执行,则当前线程等待
if(!subFlag){
try {
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
for (int i=0;i<5;i++){
System.out.println("loop:"+loop+"sub-"+Thread.currentThread().getName());
}
subFlag=false;
this.notify();
}
public synchronized void min (int loop){
if (subFlag){
try {
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
for (int i=0;i<3;i++){
System.out.println("loop:"+loop+"sub-"+Thread.currentThread().getName());
}
subFlag=true;
this.notify();
}
}
public class Test2 {
public static void main(String[] args) {
Test2 t2 = new Test2();
t2.init();
}
public void init() {
final Test t = new Test();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
t.sub(i);
}
}
});
t1.start();
for (int i = 0; i < 10; i++) {
t.min(i);
}
}
}