1.子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次
思路: 子线程循环10次,循环50次 ,然后主线程循环100次,循环50次,再通过wait,notify来协调子线程与主线程执行的顺序
总结
* 1.多线程问题简化为单线程问题(线程各自都做了什么),通过多线程的wait,notify等通讯关键字协调两个线程的执行顺序,并且因为子线程与主线程需要共用锁(竞争资源同一个Loop对象),我们最好将两个方法写在同一个类中,利于我们给其加锁,以及控制,也利于扩展和功能的整合.
* 2.wait ,notify 使用时一定要用while 来进行2次确认,防止伪唤醒情况的出现
public class WaitNotifyTest {
public static void main(String[] args) {
new WaitNotifyTest().init();
}
public void init(){
final Loop loop=new Loop();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <50 ; i++) {
loop.son(i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i <50 ; i++) {
loop.parent(i);
}
}
}).start();
}
class Loop{
private Boolean flag=true;
public synchronized void son(int i){
try {
while (!flag){
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10; j++) {
System.out.println("son time of "+j+" loop of "+i);
}
flag=false;
this.notify();
}
public synchronized void parent(int i){
try {
while (flag){
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100; j++) {
System.out.println("parent time of "+j+" loop of "+i);
}
flag=true;
this.notify();
}
}
}
欢迎大牛视察原文基地—罂粟花以及原文 http://www.poppyflower.cn/?p=108