题目:子线程循环2次,主线程循环2次,然后子线程循环2次,主线程循环2次,这样循环10次
package com.ry.test;
public class Test03 {
private boolean flag = true;
public synchronized void son() {
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 2; i++) {
System.out.println("子线程运行" + (i + 1));
}
flag = false;
this.notify();
}
public synchronized void fathor() {
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 2; i++) {
System.out.println("主线程运行" + (i + 1));
}
flag = true;
this.notify();
}
public static void main(String[] args) {
//子线程循环2次,主线程循环2次,然后子线程循环2次,主线程循环2次,这样循环10次
Test03 t = new Test03();
Thread thread = new Thread(new runnable3(t));
thread.start();
for (int i = 0; i < 10; i++) {
t.fathor();
}
}
}
class runnable3 implements Runnable {
Test03 t;
public runnable3(Test03 t) {
this.t = t;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
t.son();
}
}
}