synchronized

 

对象锁:synchronized修饰普通方法或者synchronized(this)
如下:

  public class SynTest{
    private synchronized void test1(){}


    private void test2(){
      synchronized(this){}
    }
  }

  SynTest SynTest1=new SynTest()
  Thread t1 = new Thread(SynTest1.test1());
  Thread t2 = new Thread(SynTest1.test2());
  注:相同锁


类锁:静态方法或者修饰一个类的class对象
  public class SynTest{
    private static synchronized void test1(){}
    private void test2(){
      synchronized(SynTest.class){}
    }
  }
  SynTest SynTest1=new SynTest()
  Thread t1 = new Thread(SynTest1.test1());
  Thread t2 = new Thread(SynTest1.test2());
  注:相同锁