Semaphore 和 CountDownLatch 组合使用,报异常
CountDownLatch 单独使用
CountDownLatch 这样单独使用没有问题 - 做多线程的倒计时
private final static Integer count = 6;
public static void main(String[] args) throws InterruptedException {
countDownLatchTest();
}
public static void countDownLatchTest() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(count);
for (int i = 0; i < count; i++) {
new Thread(() -> {
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName() + "~~~倒计时~~~count=" + countDownLatch.getCount());
}, "Thread-Name-" + i).start();
}
countDownLatch.await();
System.out.println(Thread.currentThread().getName() + "~~~OVER");
}
Semaphore 单独使用
Semaphore 这样单独使用也没有问题,多线程多窗口
private final static Integer count = 3;
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore(count);
for (int i = 0; i < count * count; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "~~~抢到线程");
int rand = RandomUtils.getRandom(5);
TimeUnit.SECONDS.sleep(rand);
System.out.println(Thread.currentThread().getName() + "~~~执行" +rand + "秒后,离开~~");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, "Thread-Name-" + i).start();
}
System.out.println(Thread.currentThread().getName() + "~~~OVER");
}
但是当我想要组合使用时报错,如下写法
private final static Integer count = 3;
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(count * count);
Semaphore semaphore = new Semaphore(count);
for (int i = 0; i < count * count; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "~~~抢到线程");
int rand = RandomUtils.getRandom(15);
TimeUnit.SECONDS.sleep(rand);
System.out.println(Thread.currentThread().getName() + "~~~执行" +rand + "秒后,离开~~");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
countDownLatch.countDown();
}
}, "Thread-Name-" + i).start();
}
countDownLatch.wait();
System.out.println(Thread.currentThread().getName() + "~~~OVER");
}
上述代码会在执行 countDownLatch.wait(); 语句的时候报错
Exception in thread "main" java.lang.IllegalMonitorStateException
at java.lang.Object.wait(Native Method)
at java.lang.Object.wait(Object.java:502)
at com.ax.ieng.pmcallout.test.demo.SemaphoreDemo.main(SemaphoreDemo.java:32)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
countDownLatch.wait();
改为countDownLatch.await();