0
public class SynchronizedTest
{
  public static void main(String argv[])
  { 
     Thread t1 = new Thread(new Runnable(){public void run()
     {
        synchronized (this)    //line 7
        {
            for(int i=0; i<100; i++)
                System.out.println("thread A "+i);
        }

    }});
    t1.start();
    synchronized(t1)       // line 15
    {
        for(int i=0; i<100; i++)
            System.out.println("thread B "+i);
    }
  }     
} 

如果我理解正确,那么在第 7 行同步块引用对象t1,在第 15 行同步块也引用同一个对象,因此一次只有一个线程可以获取该对象的锁,其他线程必须等待。

那他们为什么要争执呢?输出混合像

   thread B 62
   thread B 63 
   thread B 64
   thread A 0
   thread A 1
   thread A 2
   thread B 65
   thread A 3
4

1 回答 1

2

您没有使用相同的实例进行锁定。

thisRunnable实例并且t1Thread实例

我更喜欢声明private static Object LOCK = new Object();,这是内存中最小的实例,很容易知道它的用途。

从评论中编辑(由 Steffen Frank 撰写)

这与 有一些相似之处,synchronized(MyClass.class)但由于任何人都可以访问 的这个实例MyClass.class,任何人都可以使用这个锁,所以任何人都可以创建一个死锁,使用一个特定的实例给你手,如果你愿意,你可以分享它。

于 2017-05-03T12:16:28.390 回答