首页 > 编程语言 > 详细

java 几种锁实现

时间:2019-05-16 10:06:38      阅读:114      评论:0      收藏:0      [点我收藏+]
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 synchronized 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

java 几种锁实现

原文:https://www.cnblogs.com/gyli20170901/p/10873777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!