公平锁和非公平锁

转载于《Java多线程核心技术》

定义:
公平锁:按照线程加锁的顺序来分配,即先来先得FIFO;
非公平锁:一种获取锁的抢占机制,是随机的获得锁的,这样可能会有些线程一直会拿不到锁,结果也就是不公平的。

1.公平锁实例代码:

package test.Thread4;


import java.util.concurrent.locks.ReentrantLock;

class Service{
    private ReentrantLock lock;

    public Service(boolean isFair) {
        lock = new ReentrantLock(isFair);//true为公平锁
    }

    public void serviceMethod(){
        try{
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"获得锁");
        }finally {
            lock.unlock();
        }
    }
}
public class FaieLock {
    public static void main(String[] args) {
        final Service service = new Service(true);
        Runnable runnable = new Runnable() {
            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();
        }
    }
}

输出结果:

Thread-0运行了
Thread-1运行了
Thread-2运行了
Thread-1获得锁
Thread-2获得锁
Thread-0获得锁
Thread-3运行了
Thread-3获得锁
Thread-4运行了
Thread-4获得锁
Thread-5运行了
Thread-5获得锁
Thread-6运行了
Thread-6获得锁
Thread-8运行了
Thread-8获得锁
Thread-7运行了
Thread-7获得锁
Thread-9运行了
Thread-9获得锁


2.非公平锁示例代码:

package test.Thread4;


import java.util.concurrent.locks.ReentrantLock;

class Service{
    private ReentrantLock lock;

    public Service(boolean isFair) {
        lock = new ReentrantLock(isFair);//true为公平锁
    }

    public void serviceMethod(){
        try{
            lock.lock();
            System.out.println(Thread.currentThread().getName()+"获得锁");
        }finally {
            System.out.println(Thread.currentThread().getName()+"释放了锁");
            lock.unlock();
        }
    }
}
public class FaieLock {
    public static void main(String[] args) {
        final Service service = new Service(false);//非公平锁
        Runnable runnable = new Runnable() {
            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();
        }
    }
}

运行结果可能为

Thread-0运行了
Thread-0获得锁
Thread-1运行了
Thread-0释放了锁
Thread-2运行了
Thread-2获得锁
Thread-2释放了锁
Thread-1获得锁
Thread-1释放了锁
Thread-3运行了
Thread-3获得锁
Thread-3释放了锁
Thread-5运行了
Thread-5获得锁
Thread-5释放了锁
Thread-6运行了
Thread-6获得锁
Thread-6释放了锁
Thread-7运行了
Thread-7获得锁
Thread-7释放了锁
Thread-8运行了
Thread-8获得锁
Thread-8释放了锁
Thread-9运行了
Thread-9获得锁
Thread-9释放了锁
Thread-4运行了
Thread-4获得锁
Thread-4释放了锁

展开阅读全文

没有更多推荐了,返回首页