首页新闻招聘找找看知识库
  • 回复:1 浏览:6 2019-12-23 17:30 来自 cn2019

    synchronized 内置锁

    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());
      注:相同锁

  • cn2019
    2019-12-24 05:38 cn2019
    //上锁
    lock.lock();
    //调用减少库存的方法
    boolean b=new Stock().reduceStock();
    //解锁
    lock.unlock();
    第1楼 回到顶楼
登录后才能评论,请先登录注册