子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次。摘自张孝祥老师线程视频源码
package test;
public class Test {
// 子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次
public static void main(String[] args) {
new Test().init();
}
private void init() {
final Business business = new Business();
new Thread() {
public void run() {
for (int i = 1; i <= 10; i++) {
business.subdo();// 子线程
}
};
}.start();
for (int i = 1; i <= 10; i++) {
// business.subdo();// 子线程
business.maindo();
}
}
class Business {
private boolean isShouldSub = true;
public void subdo() {
synchronized (Test.class) {
if (!isShouldSub) {// 如果不该子线程执行
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName()
+ " running .." + " " + i + "次");
}
isShouldSub=false;
Test.class.notifyAll();
}
}
public void maindo() {
synchronized (Test.class) {
if (isShouldSub) {
try {
Test.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 20; i++) {
System.out.println(Thread.currentThread().getName()
+ " running .." + " " + i + "次");
}
isShouldSub=true;
Test.class.notifyAll();
}
}
}
}