jssyxzy
V2EX  ›  Java

synchronized 关键字请教

  •  
  •   jssyxzy · Jun 30, 2018 · 2042 views
    This topic created in 2879 days ago, the information mentioned may be changed or developed.

    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  
       Jun 30, 2018
    效果是一样的。
    你把 this 也当成一个成员变量,这两没啥区别
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3747 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 04:16 · PVG 12:16 · LAX 21:16 · JFK 00:16
    ♥ Do have faith in what you're doing.