快捷搜索:

多线程之公平锁与非公平锁

公平与非公平锁:锁Lock分为"公平锁"和"非公平锁",公平锁标识线程获取锁的顺序是按照线程加锁的顺序来分配的,即先来先得的FIFO先进先出顺序,而非公平锁就是一种获取锁的抢占机制,是随机获得锁的,和公平锁不一样的就是先来的不一定先得到锁,这个方式可能造成某些线程一直拿不到锁,结果就是不公平的了。

1.公平锁

package LockTest;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author LiBinquan
 */
public class Service1 {
          
   
    private ReentrantLock lock;
    public Service1(boolean isFair){
          
   
        super();
        lock = new ReentrantLock(isFair);
    }
    public void serviceMethod(){
          
   
        try{
          
   
            lock.lock();
            System.out.println("ThreadName = "+Thread.currentThread().getName()+"获得锁定");
        }finally {
          
   
            lock.unlock();
        }
    }
}

运行类:

package LockTest;

/**
 * @Author LiBinquan
 */
public class RunFair {
          
   
    public static void main(String[] args) throws InterruptedException{
          
   
        final Service1 service = new Service1(true);
        Runnable runnable = new Runnable() {
          
   
            @Override
            public void run() {
          
   
                System.out.println("★线程"+Thread.currentThread().getName()+"运行了");
                service.serviceMethod();
            }
        };
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
          
   
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
          
   
            threads[i].start();
        }
    }
}

输出:

2.非公平锁

修改运行类:

package LockTest;

/**
 * @Author LiBinquan
 */
public class RunFair {
          
   
    public static void main(String[] args) throws InterruptedException{
          
   
        final Service1 service = new Service1(false);
        Runnable runnable = new Runnable() {
          
   
            @Override
            public void run() {
          
   
                System.out.println("★线程"+Thread.currentThread().getName()+"运行了");
                service.serviceMethod();
            }
        };
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
          
   
            threads[i] = new Thread(runnable);
        }
        for (int i = 0; i < 10; i++) {
          
   
            threads[i].start();
        }
    }
}

输出: 由输出可以得出公平锁和非公平锁的结论。

经验分享 程序员 职场和发展