在多執行緒操作中,我們常常會遇到需要先判斷訊號量狀態是否就緒,然後執行後續操作的場景。這裡對狀態的判斷使用的是while而不是單執行緒下常用的if。
以下示例展示了乙個簡單的生產者-消費者模型:當佇列滿的時候,阻塞set;當隊列為空的時候,阻塞get操作。
public class eventstorage
public synchronized void set() catch (interruptedexception e)
}storage.offer(new date());
system.out.printf("set: %d",storage.size());
notifyall();
}public synchronized void get() catch (interruptedexception e)
}system.out.printf("get: %d: %s",storage.
size(),((linkedlist<?>)storage).poll());
notifyall();
}}public class producer implements runnable
@override
public void run()
}}public class consumer implements runnable
@override
public void run()
}}public class main
}
while (storage.size()==maxsize) catch (interruptedexception e)
}while (storage.size()==0) catch (interruptedexception e)
}
這裡分析一下get操縱: 當某個執行緒得到鎖時storage為空,此時它應該wait,下次被喚醒時(任意執行緒呼叫notify),storage可能還是空的。因為有可能其他執行緒清空了storage。如果此時用的是if它將不再判斷storage是否為空,直接繼續,這樣就引起了錯誤。但如果用while則每次被喚醒時都會先檢查storage是否為空再繼續,這樣才是正確的操作;生產也是同乙個道理。
建議你使用LocalDateTime而不是Date
但是這三步不是原子操作 多執行緒併發如何保證執行緒安全 避免執行緒之間共享乙個 dateformat物件,每個執行緒使用時都建立一次 dateformat物件 建立和銷毀物件的開銷大 對使用format和parse方法的地方進行加鎖 執行緒阻塞性能差 使用threadlocal保證每個執行緒最多隻建...
PHP下使用多執行緒
本文以windows為例,講解安裝和使用php pthreads擴充套件。開啟 http localhost phpinfo 1 找到 php extension build 的版本 配置 php.ini 檔案,新增一行 extension php pthreads.dll重啟 apache 並檢視...
c 下使用多執行緒
執行緒主要由cup暫存器 呼叫棧 執行緒本地儲存器 thread local storage,tls 組成。cup暫存器主要記錄當前所執行執行緒的狀態,呼叫棧主要用於維護執行緒所呼叫到的記憶體和資料,tsl主要用於存放執行緒的狀態資訊。前台執行緒 只有所有的前台執行緒全部關閉,才能完成程式關閉。後台...