我明白同步的概念,但我现在肯定为什么是实现这种方式,所以我需要在这里一点点的帮助:同步队列在多线程
我有2个线程:
PeriodicalThread
将定期接收数据(假设每5秒),并把它放在一个Queue
(使用ArrayDeque
的时刻,但我不知道是否有任何其他Queue
实施,将更好地工作)
ProccessThread
将不断检查Queue
看看它是否为空。如果它不是空的,它将处理数据(FIFO)。
所以,在我第一次实现将是:
// Both threads are inner class so they have access to Queue
private Queue queue;
private boolean isReadyToProccess;
class PeriodicalThread extends Thread {
public void run() {
while(true) {
if(isNewDataAvailable) {
// create Data object
queue.add(data);
}
}
}
}
class ProcessThread extends Thread {
public void run() {
while(true) {
if(!queue.isEmpty() && isReadyToProccess) {
Data data = queue.poll();
processData(data);
}
}
}
}
private void processData(Data data) {
// this method send data over network, and the server response callback
// changes isReadyToProcess value to true.
}
然后想处理同步,我不知道我是否应该使用lock
对象时(以及它是如何实现的),或者如果已经有一个包Queue
实现,它是线程安全的(因为add()
和poll()
方法)
编辑:我忘记了标志isReadyToProcess
指示下一个队列Data
对象是...好,准备好被处理。这个标志也应该同步。
查找到'BlockingQueue'。 –
布尔标志如何告诉你有关队列中下一个对象的内容?如果队列中有很多对象呢? –