wait 和 notify关键字
主线程和子线程相互调用
package com.gyj.student;
/**
- 线程同步问题
- @author guoyajie
*/
public class Test4 {
public static void main(String[] args) {
final Busubess busubess = new Busubess();
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<50;j++){
busubess.sub();
}
}
}).start();
for(int j=0;j<50;j++){
busubess.main();
}
}
}
class Busubess{
private boolean bShouldSub = true;
public synchronized void sub(){
if(bShouldSub){
for(int i= 0 ;i<10 ;i++){
System.out.println(“子线程第几次循环” + i);
}
bShouldSub = false;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void main(){
if(!bShouldSub){
for(int i= 0 ;i<100 ;i++){
System.out.println("主线程第几次循环" + i);
}
bShouldSub = true;
this.notify();
}else{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//if替换成while 防止伪唤醒
}