當(dāng)前位置:首頁(yè) > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > 安卓開發(fā)中使用緩沖機(jī)制
1.1 功能介紹
為了適配網(wǎng)絡(luò)傳輸線程和數(shù)據(jù)處理線程的速度,并且保證所有數(shù)據(jù)不丟失,使用了緩沖技術(shù)。其實(shí)質(zhì)就是建立一個(gè)大小合適的哈希表用于存儲(chǔ)數(shù)據(jù)來(lái)模擬隊(duì)列先進(jìn)先出的效果。同時(shí),為了協(xié)調(diào)讀和寫線程,使用了同步的技術(shù)。
1.2 函數(shù)介紹
1)向緩沖中增加數(shù)據(jù)
public synchronized Boolean addBuffer(byte[] data) {
if (data != null) {
if (buffer.size() < volume) {// 確保緩存不會(huì)溢出
buffer.put(buffer.size(), data);
return true;
} else {
log.E("%%%%% buffer.size() > volume !!!! %%%%%");
return false;
}
} else {
log.E("%%%%% addBuffer() param is null !!!! %%%%%");
return false;
}
}
紅色標(biāo)記的synchronized表示同步,即:對(duì)于同一段緩沖區(qū),讀和寫操作同一時(shí)間只能進(jìn)行一種,這樣可以保證寫一半的數(shù)據(jù)被讀取的情況不會(huì)出現(xiàn)。
2)從緩沖中讀取數(shù)據(jù)
public synchronized byte[] getBuffer() {
byte[] data = null;
if (buffer.size() > 0) {
data = buffer.get(buffer.size() - 1);
buffer.remove(buffer.size() - 1);
} else {
log.E("%%%%% readBuffer.size() < 0 !!!! %%%%%");
}
return data;
}
確保只有當(dāng)緩沖的大小大于0的時(shí)候才會(huì)讀取數(shù)據(jù)。
3)向命令緩沖中增加數(shù)據(jù)
public synchronized Boolean addCmdBuffer(int cmd, int type, int id) {
byte[] cmdd = { (byte) cmd, (byte) type, (byte) id };
if (buffer.size() < volume) {
buffer.put(buffer.size(), cmdd);
return true;
} else {
log.E("%%%%% buffer.size() > volume !!!! %%%%%");
return false;
}
}
增加的命令會(huì)被傳遞到主線程,用于實(shí)時(shí)的處理特殊命令,如:按鈕按下的效果。
{
4)獲得緩存的容量
public synchronized int getVolume() {
return buffer.size();
}
用于獲得緩存的大小,緩存的大小是一個(gè)必須要實(shí)時(shí)監(jiān)控的數(shù)據(jù),溢出有可能造成程序的異常退出。
pthread_exit(0);