天天看點

thread13 - synchronized優化

package com.neutron.t13;

import java.util.concurrent.TimeUnit;

/**
 * synchronized語句優化:
 *   同步代碼塊中的語句越少越好
 */
public class T13 {
    int count = 0;

    public synchronized void run1() {
        // do some thing not need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 業務邏輯中隻有count++需要加鎖,此時不需要給整個方法加鎖
        count++;

        // do some thing not need sync
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void run2() {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 使用細力度的鎖,可以使線程争用時間變短,進而提高效率
        synchronized(this) {
            count++;
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
           

繼續閱讀