• java lock


    多线程访问同一个变量,不进行同步,会造成结果不一致。这里解决方案有很多,使用原子变量。加锁同步,使用synchronized同步。下面是一个lock demo,后面会分析lock实现原理。lock使用的是公平锁还是非公平锁等

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * Created by GuanXF on 2017/11/26.
     */
    public class TestLock {
        private static Lock lock = new ReentrantLock();
        private static int count = 0 ;
    //    private static AtomicInteger count = new AtomicInteger(0);
    
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(task);
            Thread t2 = new Thread(task1);
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            System.out.println("count = " + count);
        }
    
        static Runnable task1 = new Runnable() {
            @Override
            public void run() {
                int index = 10000;
                while(index > 0){
                    lock.lock();
                    count++;
                    lock.unlock();
    //                count.incrementAndGet();
                    index --;
                }
            }
        };
    
        static Runnable task = new Runnable() {
            @Override
            public void run() {
                int index = 10000;
                while(index > 0){
                    lock.lock();
                    count++;
                    lock.unlock();
    //                count.incrementAndGet();
                    index --;
                }
            }
        };
    }
  • 相关阅读:
    JS判断对象是否为空
    让我感动的一首歌
    获取字符串字节长度跟截取字符串字节长度
    centos7安装mysql
    python 基础
    python + 爬虫 + fiddler + 夜神模拟器 爬取app(1)
    selenium
    adb自动化农药金币
    python 引流
    Python 并行分布式框架 Celery
  • 原文地址:https://www.cnblogs.com/luckygxf/p/7900788.html
Copyright © 2020-2023  润新知