需求描述
子线程循环 10 次,主线程循环 100 次,又子线程循环 10 次,主线程循环 100 次,如此循环 50 次,写出代码实现。
代码实现
/**
* 将线程需要同步的资源包装在一个类里面,
* 不要由外层代码去控制资源同步,这样做的好处是易维护和高内聚。
*/
public class Busnice {
/**是否是到子线程执行了*/
private boolean isSubTime = true;
public synchronized void sub(int i) {
while(!isSubTime){
try {
//线程等待
this.wait(); //调用的对象一定是锁对象否则出错,此时让出 cpu,其他线程可以进入 sync 方法
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int j = 1; j <=10; j++){
System.out.println("sub thread of"+j+"---loop:"+i);
}
isSubTime = false;
//唤醒等待线程
this.notify();
}
public synchronized void main(int i) {
while(isSubTime){
try {
//线程等待
this.wait(); //调用的对象一定是锁对象否则出错
} catch (InterruptedException e) {
e.printStackTrace();
}
}
( ; j <=; j++){
System.out.println(+j++i);
}
isSubTime = ;
.notify();
}
}
{
{
();
( () {
{
( ; i <= ; i++) {
busnice.sub(i);
}
}
});
thread.start();
( ; i <= ; i++) {
busnice.main(i);
}
}
}

