对于读写问题,ZThread库专门封装了类(ReadWriteLock)来控制读写:
FairReadWriteLock (按FIFO的顺序进行读写控制):
A FairReadWriteLock maintains a balance between the order read-only access and read-write access is allowed. Threads contending for the pair of Lockable objects this ReadWriteLock provides will gain access to the locks in FIFO order.
BiasedReadWriteLock(写优先的读写控制):
A BiasedReadWriteLock has a bias toward writers. It will prefer read-write access over read-only access when many threads are contending for access to either Lockable this ReadWriteLock provides.
下面是试测试代码(文中带有注释,因此后面不再分析程序):
使用FairReadWriteLock时的运行结果: 使用BiasedReadWriteLock时的运行结果: