美文网首页
公平锁和非公平锁

公平锁和非公平锁

作者: 迷糊小生 | 来源:发表于2019-04-02 21:13 被阅读0次

    公平锁表示线程获取锁的顺序是按照线程加锁的顺序来分配的,即先来先得的FIDO先进先出顺序.

    非公平锁就是一种获取锁的抢占机制,是随机获得锁的.

    public class DemoService {
    
        private Lock lock;
    
        public DemoService(Boolean isFair) {
            this.lock = new ReentrantLock(isFair);
        }
    
        public void print() {
            lock.lock();
            try {
                System.out.println("ThreadName=" + Thread.currentThread().getName() + "锁定");
            } finally {
                lock.unlock();
            }
    
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            DemoService service = new DemoService(true);
    
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("Thread:" + Thread.currentThread().getName());
                    service.print();
                }
            };
    
            Thread[] thread = new Thread[10];
            for (int i = 0; i < 10; i++) {
                thread[i] = new Thread(runnable);
            }
            for (int i = 0; i < 10; i++) {
                thread[i].start();
            }
        }
    }
    
    image.png

    打印的结果基本呈有序状态,这就是公平锁的特点。

    将Test类中的ture改为false就变成了非公平锁了:


    image.png

    非公平锁运行结果基本是乱序的,说明先start的线程不一定先获得锁。

    相关文章

      网友评论

          本文标题:公平锁和非公平锁

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