最近学了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();
}
}
}
}
首先 你这个代码 我原样复制不做任何改动是可以直接运行的,不会报错。
然后我猜你可能是想问为什么老是是同一个线程在执行,像下面这样:
可能想的是每个线程都应该统一机会去执行,像这样:
因为线程数太少,也就是样本太少,while (true) 里面一下就过,根本感知不到停顿,线程也就机会不会切换;
把sleep放下去就能看到那样的效果了