java 几种锁实现

public class SyncronizedTest {

    private int value = 1;
    private AtomicInteger value1 = new AtomicInteger(1);
    private Lock lock = new ReentrantLock();

    //sycronized
    public synchronized int getValue() {
        return value ++ ;
    }

    //jdk自带原子操作
    public int getValue1() {
        return value1.getAndIncrement();
    }

    //lock
    public int getValue2() {
        lock.lock();
        int a = value ++ ;
        lock.unlock();
        return a;
    }

    public static void main(String[] args) {

        //此处必须使用同一个实例对象,因为synchronized锁此处针对的是对象,如果实例化2个对象相当于每个对象有一把锁
        SyncronizedTest syncronizedTest = new SyncronizedTest();
        long startTime = System.currentTimeMillis();

        Runnable runnable = () -> {
            for(int i = 0; i < 100; i ++){
                System.out.println(Thread.currentThread().getName() + ",值:" + syncronizedTest.getValue());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        thread1.start();
        Thread thread2 = new Thread(runnable);
        thread2.start();
        Thread thread3 = new Thread(runnable);
        thread3.start();
        Thread thread4 = new Thread(runnable);
        thread4.start();
        Thread thread5 = new Thread(runnable);
        thread5.start();

        while (thread1.isAlive() || thread2.isAlive() || thread3.isAlive() || thread4.isAlive() || thread5.isAlive()) {
            //自旋
        }
        long endTime = System.currentTimeMillis();
        System.out.println("耗时:"+ (endTime - startTime));
    }
}

 

性能对比说明:https://www.cnblogs.com/flying607/p/5733043.html

posted @ 2019-05-16 09:48  谋知  阅读(1137)  评论(0编辑  收藏  举报