package thread;
/**
* 子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次
*/
public class Thread4Test {
private static Object object=new Object();
private static boolean endFlag=true;
private static class ThreadMain extends Thread {
ThreadChild threadChild = new ThreadChild();
@Override
public void run() {
try {
threadChild.start();
for (int i = 1; i <= 50; i++) {
synchronized (object) {
object.wait();
}
for (int j = 0; j < 100; j++) {
System.out.println(j + 1 + "--主线程" + i);
}
synchronized (object) {
if(i==50) endFlag=false;
object.notify();
}
}
} catch (InterruptedException e) {
//do something
}
}
}
private static class ThreadChild extends Thread {
@Override
public void run() {
while (endFlag) {
synchronized (object) {
for (int i = 0; i < 10; i++) {
System.out.println(i + 1 + "--子线程");
}
try {
object.notify();
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
try {
ThreadMain threadMain = new ThreadMain();
threadMain.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}