Java中公平锁与非公平锁的区别

所谓公平锁指的是哪个线程先运行,那就可以先得到锁。非公平锁是不管线程是否是先运行,都是随机获得锁的。

看下代码就清楚了。


<strong>package FairAndUnFailLock;

public class TestMain {

	public TestMain() {
		
	}
	
	public static void main(String[] args) {
		Service service = new Service();
		ThreadClass tcArray[] = new ThreadClass[20];
		for(int i=0;i<20;i++){
			tcArray[i] = new ThreadClass(service);
			tcArray[i].start();
		}
		
	}
}




package FairAndUnFailLock;

import java.util.concurrent.locks.ReentrantLock;

public class Service {
	public ReentrantLock lock = new ReentrantLock(false);
	public Service() {
	}

	public void getThreadName() {
		System.out.println(Thread.currentThread().getName() + " 已经被锁定");
	}

}






package FairAndUnFailLock;

public class ThreadClass extends Thread{
	private Service service;
	
	public ThreadClass(Service service) {
		this.service = service;
	}
	
	public void run(){
		System.out.println(Thread.currentThread().getName() + " 抢到了锁");
		service.lock.lock();
		service.getThreadName();
		service.lock.unlock();
	}

}

</strong>


    原文作者:java锁
    原文地址: https://blog.csdn.net/wangyan199366/article/details/51895834
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞