问题是你释放信号量的次数多于获得的信号量.您应该删除while
以释放您的信号量.你应该只发布一次,所以请if
改用.
并根据您的计划produce()
,consume()
应该改为这个.
生产()
private static void produce() throws InterruptedException { int value = 0; while (true) { //try to get control & put an item. semaphore.acquire(); //but if the queue is full, give up and try again. if (integerLinkedList.size() == 10) { semaphore.release(); continue; } //if not full, put an item & release the control. integerLinkedList.add(value++); semaphore.release(); } }
消耗()
private static void consume() throws InterruptedException { while (true) { //try to get the control and consume an item. semaphore.acquire(); //but if the queue is empty, give up and try again. if (integerLinkedList.size() == 0) { semaphore.release(); continue; } //if not empty, *consume first one, *print it, *release the control and go sleep. Integer value = integerLinkedList.removeFirst(); System.out.println("Size of the List is " + integerLinkedList.size() + " and value removed is " + value); semaphore.release(); Thread.sleep(100); } }
如果你希望在更安全的一面,你可以Thread.sleep(50);
在每个break;
语句之前添加一些东西,这样你就可以给另一个线程继续执行它.
我假设您编写了典型的生产者消费者问题.如果您想让我改变一下,请告诉我.无论如何希望这可以解决你的基本问题.:))
问题是你释放信号量的次数多于获得的信号量.您应该删除while
以释放您的信号量.你应该只发布一次,所以请if
改用.
并根据您的计划produce()
,consume()
应该改为这个.
生产()
private static void produce() throws InterruptedException { int value = 0; while (true) { //try to get control & put an item. semaphore.acquire(); //but if the queue is full, give up and try again. if (integerLinkedList.size() == 10) { semaphore.release(); continue; } //if not full, put an item & release the control. integerLinkedList.add(value++); semaphore.release(); } }
消耗()
private static void consume() throws InterruptedException { while (true) { //try to get the control and consume an item. semaphore.acquire(); //but if the queue is empty, give up and try again. if (integerLinkedList.size() == 0) { semaphore.release(); continue; } //if not empty, *consume first one, *print it, *release the control and go sleep. Integer value = integerLinkedList.removeFirst(); System.out.println("Size of the List is " + integerLinkedList.size() + " and value removed is " + value); semaphore.release(); Thread.sleep(100); } }
如果你希望在更安全的一面,你可以Thread.sleep(50);
在每个break;
语句之前添加一些东西,这样你就可以给另一个线程继续执行它.
我假设您编写了典型的生产者消费者问题.如果您想让我改变一下,请告诉我.无论如何希望这可以解决你的基本问题.:))