内部锁、不公平锁、公平锁机制小例子_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 内部锁、不公平锁、公平锁机制小例子

内部锁、不公平锁、公平锁机制小例子

 2012/6/18 16:28:00  wsp_java  程序员俱乐部  我要评论(0)
  • 摘要:下面举的例子,统计了三种同步锁(内部锁、不公平锁、公平锁)并发执行时消耗的时间publicinterfaceCounter{publiclonggetValue();publicvoidincrement();}/***内部锁*/publicclassSynchronizedBenchmarkDemoimplementsCounter{privatelongcount=0;@OverridepubliclonggetValue(){returncount;
  • 标签:例子

下面举的例子,统计了三种同步锁(内部锁、不公平锁、公平锁)并发执行时消耗的时间

?

public interface Counter {
    public long getValue();
    public void increment();
}

?

/**
 * 内部锁
 */
public class SynchronizedBenchmarkDemo implements Counter {
    private long count = 0;

    @Override
    public long getValue() {
        return count;
    }

    @Override
    public synchronized void increment() {
        count++;
    }

}
?

?

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 不公平锁
 */
@SuppressWarnings("all")
public class ReentrantLockUnfairBeanchmarkDemo implements Counter {
    private volatile long count = 0;
    private Lock lock;

    public ReentrantLockUnfairBeanchmarkDemo() {
        // 使用不公平锁
        lock = new ReentrantLock(false);
    }

    @Override
    public long getValue() {
        return count;
    }

    @Override
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

}
?

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 公平重入锁
 */
@SuppressWarnings("all")
public class ReentrantLockFairBeanchmarkDemo implements Counter {
    private volatile long count = 0;
    private Lock lock;

    public ReentrantLockFairBeanchmarkDemo() {
        // 创建公平锁
        lock = new ReentrantLock(true);
    }

    @Override
    public long getValue() {
        return count;
    }

    @Override
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

}

?

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 三种类型的同步锁:内部锁、不公平锁、公平锁,每种类型的锁各自创建2000个线程,然后每个线程访问带有锁得变量100次,并加1。
 * 统计各种锁并发访问时消耗的时间
 *
 * @author Administrator
 *
 */
@SuppressWarnings("all")
public class BenchmarkTest {
    private Counter counter;
    // 一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点
    private CyclicBarrier barrier;
    private int threadNum;
    private int loopNum;
    private String testName;
    /*******************************************************************
     * 用于记录由该对象创建的threadNum线程统开始循环和结束循环的起止时间
     */
    public long begin;
    public long end;

    private BenchmarkTest(Counter counter, int threadNum, int loopNum, String testName) {
        this.counter = counter;
        this.threadNum = threadNum;
        this.loopNum = loopNum;
        this.testName = testName;
        barrier = new CyclicBarrier(threadNum, new BarrierTime(this));
    }

    public void test() {
        try {
            for (int i = 0; i < threadNum; i++) {
                new TestThread(counter, loopNum, this).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            int threadNum = 2000;
            int loopNum = 100;

            new BenchmarkTest(new SynchronizedBenchmarkDemo(), threadNum, loopNum, "内部锁").test();
            Thread.sleep(5000);

            new BenchmarkTest(new ReentrantLockUnfairBeanchmarkDemo(), threadNum, loopNum, "不公平锁").test();
            Thread.sleep(5000);

            new BenchmarkTest(new ReentrantLockFairBeanchmarkDemo(), threadNum, loopNum, "公平锁锁").test();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    class TestThread extends Thread {
        int loopNum = 100;
        private Counter counter;
        private BenchmarkTest benchmarkTest;

        private TestThread(final Counter counter, int loopNum, BenchmarkTest benchmarkTest) {
            this.counter = counter;
            this.loopNum = loopNum;
            this.benchmarkTest = benchmarkTest;
        }

        public void run() {
            try {
                // 等待所有线程开始
                barrier.await();
                for (int i = 0; i < this.loopNum; i++) {
                    counter.increment();
                }
                // 等待所有线程结束
                barrier.await();
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
    }

    class BarrierTime implements Runnable {
        private BenchmarkTest benchmarkTest;

        public BarrierTime(BenchmarkTest benchmarkTest) {
            this.benchmarkTest = benchmarkTest;
        }

        @Override
        public void run() {
            if (benchmarkTest.begin == 0) {
                benchmarkTest.begin = System.currentTimeMillis();
            } else {
                benchmarkTest.end = System.currentTimeMillis();
            }
            if (benchmarkTest.end != 0) {
                System.out.println(benchmarkTest.testName + "共花费时间:" + (benchmarkTest.end - benchmarkTest.begin) + "毫秒");
            }
        }

    }
}
?
发表评论
用户名: 匿名