synchronized 和 Reentrantlock簡單例子對比

  我的博客地址:http://www.cnblogs.com/wdfwolf3/。轉載註明出處,謝謝。ide

  兩個鎖的對比就再也不贅述,直接上代碼。兩次實驗,第一次是固定5個線程,調整每一個線程的循環次數,獲得的運行時間。第二次是每一個線程的循環次數固定10000000,調整線程數,獲得的運行時間。this

/**
 * 5個線程,每一個循環次數          100000  1000000  10000000  100000000
 * synchronized(ms)              29      265      3293     47789
 * ReentrantLock(ms)             79      165      1473     14923
 * volatile(ms)                  count++非原子操做不能同步
 * 
 * 10000000次 線程數       2     5     8    15
 * synchronized(ms)     661   3293  7084  11380
 * ReentrantLock(ms)    767   1473  2342  3672
 */
public class SynchronizedTest {
    public static void main(String[] args) {
        //線程數
        int threadNum = 5;
        Syn syn = new Syn();
        Thread[] threads = new Thread[threadNum];
        //記錄運行時間
        long l = System.currentTimeMillis();
        for (int i = 0; i < threadNum; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 10000000; j++) {
                        syn.increaseLock();
                    }
                }
            });
            threads[i].start();
        }
        //等待全部線程結束
        try {
            for (int i = 0; i < threadNum; i++)
                threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(syn + " : " + (System.currentTimeMillis() - l) + "ms");
    }
}

class Syn {
    private int count = 0;
    private Lock lock = new ReentrantLock();

    //利用synchronized
    public void increase() {
        synchronized (this) {
            count++;
        }
    }

    //利用ReentrantLock類同步
    public void increaseLock() {
        lock.lock();
//        if (count == 5000000)
//            System.out.println(lock);
        count++;
        lock.unlock();
    }

    public void increaseVolatile() {
        count = count + 1;
    }

    @Override
    public String toString() {
        return String.valueOf(count);
    }
}
相關文章
相關標籤/搜索