class TicketsThread implements Runnable { int tickets = 0; Lock lock = new ReentrantLock();//放到run方法外面就可以了,跟tickets一样,都属于共享资源,就一把锁才好使 public void run() {}
The Java programming language provides multiple mechanisms for communicating between threads. The most basic of these methods is synchronization, which is implemented using monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor. Any other threads attempting to lock that monitor are blocked until they can obtain a lock on that monitor. A thread t may lock a particular monitor multiple times; each unlock reverses the effect of one lock operation. --java language specification
class TicketsThread implements Runnable {
int tickets = 0;
Lock lock = new ReentrantLock();//放到run方法外面就可以了,跟tickets一样,都属于共享资源,就一把锁才好使
public void run() {}
现在我有点疑问:在同一对象上能加不同的锁,如果这是对的话;那jvm为每一个对象关联了唯一的一把锁,又怎么解释?
你说的是使用synchronized的时候吧,但是,你的例子使用的是Lock,如果使用jdk1.4的话,你就没有这样的疑问了。lock是jdk5以后才提供的。
--java language specification
Lock lock = new ReentrantLock();放到属性的声明中,不要放在run方法里。
这样,因为三个线程都使用了共同的tt,tt的lock属性是同一个,这样三个线程间就互相有干涉了。