*
编写程序实现,子线程循环3次,接着主线程循环5次,
接着再子线程循环3次,主线程循环5次,如此反复,循环3次
*/
public class Work4 {
private static boolean flag = false;
//定义子线程循环输出次数
private static int count1 = 1;
//定义主线程循环输出次数
private static int count2 = 1;
public static void main(String[] args) {
//创建主方法的类为锁对象
Work4 work4 = new Work4();
//定义匿名内部类实现的子线程,和主线程共享主方法类的对象
new Thread(new Runnable() {
@Override
public void run() {
synchronized (work4) {
//设定子线程循环次数
while (count1 < 4) {
if (!flag) {
for (int j = 0; j < 3; j++) {
System.out.println(Thread.currentThread().getName() + "的第" +
count1 + "第" + (j + 1) + "次循环!");
}
count1++;
flag = true;
work4.notifyAll();
} else {
try {
work4.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}, "子线程").start();
//设定主线程循环次数
while (count2 < 4) {
synchronized (work4) {
if (flag) {
for (int j = 0; j < 5; j++) {
System.out.println(Thread.currentThread().getName() + "的第" +
count2 + "第" + (j + 1) + "次循环!");
}
count2++;
flag = false;
work4.notifyAll();
} else {
try {
work4.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
编写程序实现,子线程循环3次,接着主线程循环5次, 接着再子线程循环3次,主线程循环5次,如此反复,循环3次
![](https://img-home.csdnimg.cn/images/20240711042549.png)