3 回答

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
而不是讓 Consumerextend Runnable你可以改變你的代碼來合并一個(gè)ScheduledExecutorService每半秒運(yùn)行一次隊(duì)列輪詢而不是讓線程休眠的代碼。這方面的一個(gè)例子是
public void schedule() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(() -> {
String str;
try {
while ((str = queue.poll()) != null) {
call(str); // do further processing
}
} catch (IOException e) {
ferpt.felog("svr class", "consumer", "consumer thread", e.getClass().getName() + ": " + e.getMessage());
}
}, 0, 500, TimeUnit.MILLISECONDS);
}

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
解決您的問題的正確方法是使用阻塞隊(duì)列。它為您提供了幾個(gè)優(yōu)勢:
不浪費(fèi)cpu忙等待
容量有限 - 假設(shè)你有一個(gè)快速的生產(chǎn)者,但一個(gè)緩慢的消費(fèi)者 -> 如果隊(duì)列的大小不受限制,那么你的應(yīng)用程序很容易達(dá)到 OutOfMemory 條件
這是一個(gè)小演示,您可以使用它:
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ProdConsTest {
public static void main(String[] args) throws InterruptedException {
final BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
final Runnable producer = () -> {
for (int i = 0; i < 1000; i++) {
try {
System.out.println("Producing: " + i);
queue.put(i);
//Adjust production speed by modifying the sleep time
Thread.sleep(100);
} catch (InterruptedException e) {
//someone signaled us to terminate
break;
}
}
};
final Runnable consumer = () -> {
while (true) {
final Integer integer;
try {
//Uncomment to simulate slow consumer:
//Thread.sleep(1000);
integer = queue.take();
} catch (InterruptedException e) {
//someone signaled us to terminate
break;
}
System.out.println("Consumed: " + integer);
}
};
final Thread consumerThread = new Thread(consumer);
consumerThread.start();
final Thread producerThread = new Thread(producer);
producerThread.start();
producerThread.join();
consumerThread.interrupt();
consumerThread.join();
}
}
現(xiàn)在取消注釋sleep()消費(fèi)者并觀察應(yīng)用程序發(fā)生了什么。如果您正在使用基于計(jì)時(shí)器的解決方案,例如建議的解決方案,ScheduledExecutorService或者您正忙于等待,那么使用快速生產(chǎn)者,隊(duì)列將無法控制地增長并最終導(dǎo)致您的應(yīng)用程序崩潰

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
當(dāng)有新消息時(shí),讓消費(fèi)者wait()
在一個(gè)對(duì)象上都可以訪問,并讓生產(chǎn)者在這個(gè)對(duì)象上監(jiān)聽。notify()
然后,消費(fèi)者應(yīng)該刪除所有消息,而不僅僅是示例中的單個(gè)消息。
添加回答
舉報(bào)