ReentrantLock and Synchronized (from peter)


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class HighContentionSimulator implements Runnable {
    enum Mode implements Runnable {
        LOCK {
            private final Lock lock = new ReentrantLock();
            public void run() {
                lock.lock();
                try {
                    operation();
                } finally {
                    lock.unlock();
                }
            }},
        SYNC {
            public synchronized void run() {
                operation();
            }}
    }
 
    private final Mode mode;
    private final int count;
 
    public HighContentionSimulator(Mode mode, int count) {
        this.mode = mode;
        this.count = count;
    }
 
    public void run() {
        for (int i = 0; i < count; i++)
            mode.run();
    }
 
    public static void operation() {
        Double d = Math.random();
    }
 
    private static void test(Mode mode) throws InterruptedException {
        int threadNumber = 4;
        int count = 1000 * 1000;
        long start = System.nanoTime();
        Thread[] threads = new Thread[threadNumber];
        for (int i = 0; i < threadNumber; i++)
            (threads[i] = new Thread(new HighContentionSimulator(mode, count))).start();
        for (int i = 0; i < threadNumber; i++)
            threads[i].join();
        long rate = 1000L * 1000 * 1000 * count * threadNumber / (System.nanoTime() - start);
        System.out.printf("%s operations/second %,d%n", mode.toString(), rate);
    }
 
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 3; i++) {
            test(Mode.LOCK);
            test(Mode.SYNC);
        }
    }
}


Prints

LOCK operations/second 2,722,306
SYNC operations/second 967,460
LOCK operations/second 2,838,865
SYNC operations/second 972,421
LOCK operations/second 2,848,031
SYNC operations/second 1,094,899

你可能感兴趣的:(thread)