标签:
公平与非公平锁:锁Lock分为“公平锁”和“非公平锁”,公平锁表示线程获取锁的顺序是按照线程加锁的顺序来分配的,即先来先得的FIFO先进先出顺序。而非公平锁就是一种获取锁的抢占机制,是随机获得锁的,和公平锁不一样的就是先来的不一定先得到锁,这个方式可能造成某些线程一直拿不到锁,结果也就是不公平的了。1、公平锁实例
public class Service { private ReentrantLock lock ; public Service(boolean isFair) { lock = new ReentrantLock(isFair); } public void serviceMethod() { try { lock.lock(); System.out.println("ThreadName=" + Thread.currentThread().getName() + " 获得锁定"); } finally { lock.unlock(); } } }
public class Run { public static void main(String[] args) throws InterruptedException { final Service service = new Service(true); //改为false就为非公平锁了 Runnable runnable = new Runnable() { public void run() { System.out.println("**线程: " + Thread.currentThread().getName() + " 运行了 " ); service.serviceMethod(); } }; Thread[] threadArray = new Thread[10]; for (int i=0; i<10; i++) { threadArray[i] = new Thread(runnable); } for (int i=0; i<10; i++) { threadArray[i].start(); } } }
**线程: Thread-0 运行了 ThreadName=Thread-0 获得锁定 **线程: Thread-1 运行了 ThreadName=Thread-1 获得锁定 **线程: Thread-4 运行了 **线程: Thread-5 运行了 ThreadName=Thread-4 获得锁定 **线程: Thread-3 运行了 **线程: Thread-7 运行了 **线程: Thread-9 运行了 ThreadName=Thread-5 获得锁定 ThreadName=Thread-3 获得锁定 **线程: Thread-2 运行了 ThreadName=Thread-7 获得锁定 ThreadName=Thread-9 获得锁定 ThreadName=Thread-2 获得锁定 **线程: Thread-6 运行了 ThreadName=Thread-6 获得锁定 **线程: Thread-8 运行了 ThreadName=Thread-8 获得锁定 |
--------------------------------------------------------------------------
把Run类里的true改为false就为非公平锁了
**线程: Thread-1 运行了 **线程: Thread-4 运行了 ThreadName=Thread-1 获得锁定 **线程: Thread-3 运行了 ThreadName=Thread-4 获得锁定 **线程: Thread-6 运行了 **线程: Thread-5 运行了 **线程: Thread-2 运行了 **线程: Thread-0 运行了 ThreadName=Thread-6 获得锁定 **线程: Thread-7 运行了 ThreadName=Thread-7 获得锁定 **线程: Thread-8 运行了 ThreadName=Thread-8 获得锁定 ThreadName=Thread-3 获得锁定 **线程: Thread-9 运行了 ThreadName=Thread-9 获得锁定 ThreadName=Thread-5 获得锁定 ThreadName=Thread-2 获得锁定 ThreadName=Thread-0 获得锁定 |
标签:
原文地址:http://blog.csdn.net/ochangwen/article/details/51340636