java中synchronized用法基本总结

对于synchronized,基本理解就是可以把任何一个非null对象作为”锁”

1、作用在方法上时,锁住的便是对象实例(this)

public class SynchronizedObject {
    /*
     * 当synchronized作用在方法上时,锁住的便是对象实例(this)
     * */
    public synchronized void doSomething() {
        System.out.println("task start......");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task end......");
    }
}

2、作用在静态方法时锁住的便是对象对应的Class实例

/*
 * 当作用在静态方法时锁住的便是对象对应的Class实例,
 * 因为Class数据存在于永久带,因此静态方法锁相当于该类的一个全局锁
 * */
public class StaticSynchronizedFunction {
    public static synchronized void doSomething() {
        System.out.println("task start......");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("task end......");
    }
}

3、使用自身对象(this)上锁,锁住的便是对象实例(this)

public class SynchronizedObject {
    public void doSomething1() {
        // 直接锁定对象实例(this)
        synchronized(this) {
            System.out.println("task1 start......");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task1 end......");
        }
    }
}

4、使用class上锁,锁住的便是对象对应的Class实例

public class SynchronizedObject {
    public void doSomething2() {
        // 锁住的对象对应的Class实例
        synchronized(SynchronizedObject.class) {
            System.out.println("task2 start......");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("task2 end......");
        }
    }
}

5、结合需要,灵活的使用自定义对象上锁

Object lock = new Object();
for (int i = 0; i < 10; i++) {
    new Thread() {
        @Override
        public void run() {
            synchronized(lock) {
                System.out.println("task2 start......");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("task2 end......");
            }
        }

    }.start();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值