V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
jssyxzy
V2EX  ›  Java

synchronized 关键字请教

  •  
  •   jssyxzy · 2018-06-30 15:12:15 +08:00 · 1599 次点击
    这是一个创建于 2120 天前的主题,其中的信息可能已经有所发展或是发生改变。

    http://www.importnew.com/21866.html

    我理解下面两种用法相同不知道对不对,请指教。

    1. 修饰一个代码块
       public  void run() {
          synchronized(this) {
             for (int i = 0; i < 5; i++) {
                try {
                   System.out.println(Thread.currentThread().getName() + ":" + (count++));
                   Thread.sleep(100);
                } catch (InterruptedException e) {
                   e.printStackTrace();
                }
             }
          }
       }
    
    1. 指定要给某个对象加锁
       public void run() {
          synchronized (account) {
             account.deposit(500);
             account.withdraw(500);
             System.out.println(Thread.currentThread().getName() + ":" + account.getBalance());
          }
       }
    
    seancheer
        1
    seancheer  
       2018-06-30 17:32:02 +08:00
    效果是一样的。
    你把 this 也当成一个成员变量,这两没啥区别
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   890 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:02 · PVG 06:02 · LAX 15:02 · JFK 18:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.