问题遇到的现象和发生背景
最近学了JUC,写了一个枪的生产者消费者案例,但是在运行的时候,总是没有任何异常的退出了,感觉是源代码的问题,求帮助。
问题相关代码,请勿粘贴截图
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
@SpringBootTest
public class test1 {
@Test
public void test1(){
Gun gun = new Gun();
for (int j = 0; j < 3; j++) {
new Thread(()->{
try {
gun.reloadBuillet();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "reload"+j).start();
}
for (int i = 0; i < 3; i++) {
new Thread(()->{
try {
gun.biuBullet();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "biu"+i).start();
}
}
class Gun {
private int bulletNumber=5;//枪膛的子弹数
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Condition empty = lock.newCondition();
public void biuBullet() throws InterruptedException {
while (true){
try {
lock.lock();
while (bulletNumber<=0){
empty.await();
}
condition.signalAll();
bulletNumber--;
System.out.println(Thread.currentThread().getName()+"biu了一下"+"剩余"+bulletNumber);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public void reloadBuillet() throws InterruptedException {
while (true){
try {
lock.lock();
while (bulletNumber>20){
condition.await();
}
empty.signalAll();
bulletNumber++;
System.out.println(Thread.currentThread().getName()+"reload了一下"+"剩余"+bulletNumber);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}


