天天看点

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();
        }
    }
}
           

继续阅读