java lock

作者: java部落 | 来源:发表于2017-11-28 18:50 被阅读0次

    多线程访问同一个变量,不进行同步,会造成结果不一致。这里解决方案有很多,使用原子变量。加锁同步,使用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 --;
                }
            }
        };
    }
    

    欢迎加入学习交流群569772982,大家一起学习交流。

    相关文章

      网友评论

          本文标题:java lock

          本文链接:https://www.haomeiwen.com/subject/zqiebxtx.html