如果你程序段里有synchronization,一个对象对应一个monitors。
monitors高兴了,没有我,你去不了cpu,如果你去了cpu,我还要保证你执行完了,别人才能执行,重要吧!
一、功能
1、线程通过它才能去Cpu执行。
2、它保存(一个对象,锁)数据。
对象 锁计数
01 1
01 2
01 0 :表示所有对象都默认一个空锁。
3、jvm一看见 synchronization这个,表示随后的代码段要用共享数据了,哪么把把对象和monitors连接起来
二、
1》A monitor supports two kinds of thread synchronization:mutual exclusion andcooperation 一个监控支持两种线程 synchronization:互斥和合作关系。
2》Mutual exclusion, which is supported in the Java Virtual Machine via object locks
互斥:对象锁实现,表示各干各的,在critical section执行完后,退出。 合作关系:通过多个线程通过wait and notify 方法,或 a Signal and Continue 允许在critical section时,停下来,让另一个线程执行。 三、例子:只要获得monitor后才能进入就绪队列等待Cpu执行。 1、 A monitor is like a building that contains one special room that can be occupied by only one thread at a time. 一个monitor:像一栋房子,里面有一个特殊的房间,在一个时间点上仅仅一个线程住在里面。 房间里包含一些数据,只有住在里面的线程独自享受。 进入monitor 房子:entering the monitor(进入monitor) 进入特殊房间:acquiring the monitor(获得monitor) 正住在房间: owning the monitor(拥有monitor) 离开房间: releasing the monitor(释放monitor) 离开这栋房子:exiting the monitor(退出monitor) 正住在房间:当一个cpu正在执行synchronization块时,一个线程也住在monitor的特殊房间里面。 Entry Set:表示一栋房子的大厅。 the owner:占有房间的线程。 Wait Set:正在执行的线程必须等待另一个线程执行完,才能执行,wait()进入Wait Set列表。 2、a monitor除了和数据相连,还和一段代码(叫重点区critical sections)相连 四、线程的没有时间片去轮流使用Cpu,只有高,低优先级,哪么高优先级先如果不被blocked 一直在Cpu里执行,哪么低优先级的线程怎么办? If an object has no instance variables, or a classhas no class variables, the associated monitor protects no data:即当一个对象没有实例变量,一个类没有类变量时,关联的monitor 保护没有数据的线程。 a monitor:让低优先级的线程的得到Cpu。 五、 mutual exclusion helps keep threads from interfering with one another while sharing data, cooperation helps threads to work together towards some common goal.
