本帖最后由 wnczwl369 于 2011-05-28 03:20:26 编辑

解决方案 »

  1.   

    在同一对象上能加不同的锁,如果这是对的话;那jvm为每一个对象关联了唯一的一把锁,又怎么解释。?谢了。
      

  2.   


    class TicketsThread implements Runnable {
    int tickets = 0;
    Lock lock = new ReentrantLock();//放到run方法外面就可以了,跟tickets一样,都属于共享资源,就一把锁才好使
    public void run() {}
      

  3.   

    首先 ,楼上说的对。
    现在我有点疑问:在同一对象上能加不同的锁,如果这是对的话;那jvm为每一个对象关联了唯一的一把锁,又怎么解释?
      

  4.   

    那jvm为每一个对象关联了唯一的一把锁?
    你说的是使用synchronized的时候吧,但是,你的例子使用的是Lock,如果使用jdk1.4的话,你就没有这样的疑问了。lock是jdk5以后才提供的。
      

  5.   

    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
      

  6.   

    http://product.dangdang.com/product.aspx?product_id=8981994
      

  7.   

    LZ首先要清楚一点,只有多个线程同时访问同一个资源,才会有同步的问题,你的三个线程,分别new了三个lock,每个lock各不相干,所以三个线程也不会互相有影响。在你这个程序中,把lock作为TicketsThread的属性就可以了,,即
    Lock lock = new ReentrantLock();放到属性的声明中,不要放在run方法里。
    这样,因为三个线程都使用了共同的tt,tt的lock属性是同一个,这样三个线程间就互相有干涉了。