wait和notify主要应用在线程暂停和唤醒,wait会让出锁资源,所以在notify唤醒该线程时,需要重新竞争锁资源
简单的代码实现如下:
private static int maxLoadNum = 20;
private int bulltNum = 0;
private synchronized void putBullt(){
if (bulltNum >= maxLoadNum) {
try {
Log.d("ZTL", "Loader,,,,,,wait!");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(bulltNum < maxLoadNum) {
bulltNum++;
Log.d("ZTL", "Loader,,,,,," + bulltNum);
}
notifyAll();
}
private synchronized void shootBullt(){
if(bulltNum == 0){
try {
Log.d("ZTL", "Shooter,,,,,,wait!");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(bulltNum > 0) {
bulltNum--;
Log.d("ZTL", "Shooter,,,,,," + bulltNum);
}
notifyAll();
}
class LoaderThread extends Thread {
@Override
public void run() {
super.run();
for(int i = 0;i < 100;i ++){
putBullt();
}
}
}
class ShooterThread extends Thread{
@Override
public void run() {
super.run();
while(true){
shootBullt();
}
}
}