本帖最后由 黄小贝 于 2013-11-13 18:24 编辑
Synchronization is achieved using monitors. Every object can have a monitor associated with it, so any object can synchronize blocks. Before a synchronized block can be entered, a thread needs to gain ownership of the monitor for that block. Once the thread has gained ownership of the monitor, no other thread synchronized on the same monitor can gain entry to that block (or any other block or method synchronized on the same monitor). The thread owning the monitor gets to execute all the statements in the block, and then automatically releases ownership of the monitor on exiting the block. At that point, another thread waiting to enter the block can acquire ownership of the monitor.
每一个对象都有一个监听器(monitor),每一个synchronizad()代码块的括号里面的都是一个对象, 当一个线程试图进入synchronizad的代码块的时候,会试图得到这个对象的monitor,其他处于同一 monitor下面的其他线程想要进入synchronizad代码块的时候就必须等待这个线程释放monitor,一个线程执行完synchronizad代码块后会自动释放monitor。
synchronizad作用于多个线程之间,你的程序里面,thread 1 首先进入 run 里面,也就得到了你ticket对象的monitor,因为是synchronizad的,所以,其他线程必须等thread 1 执行完释放 monitor 才会进入,可是那个时候票已经被卖完了
你注释的程序里面,也是有问题的,楼上已经验证
|