Java多线程18:公平锁与非公平锁
前言
公平锁与非公平锁:锁Lock分为“公平锁”和“非公平锁”,公平锁表示线程获取锁的顺序是按照线程加锁的顺序来分配的,即先来先得的FIFO先进先出顺序。而非公平锁就是一种获取锁的抢占机制,是随机获取锁的,和公平锁不一样的就是先来的不一定先得到锁,这个方式可能造成某些线程一直拿不到锁,结果也就是不公平得了。
创建公平锁
package unit3;
import java.util.concurrent.locks.ReentrantLock;
/**
* 公平锁
* @author Administrator
*
*/
public class Demo9_Run {
public static void main(String[] args) {
//公平锁
final Demo9Service service = new Demo9Service(true);
//非公平锁
//final Demo9Service service = new Demo9Service(false);
Runnable runnalbe = new Runnable() {
@Override
public void run() {
System.out.println("#线程" + Thread.currentThread().getName() + "运行了");
service.serviceMethod();
}
};
Thread[] threadArray = new Thread[20];
for (int i = 0; i < 20; i++) {
threadArray[i] = new Thread(runnalbe);
}
for (int i = 0; i < 20; i++) {
threadArray[i].start();
}
}
}
class Demo9Service {
private ReentrantLock lock;
public Demo9Service(boolean isFair) {
super();
lock = new ReentrantLock(isFair);
}
public void serviceMethod() {
try {
lock.lock();
System.out.println("ThreadName=" +
Thread.currentThread().getName() + "获得锁");
} finally {
lock.unlock();
}
}
}
创建非公平锁
package unit3;
import java.util.concurrent.locks.ReentrantLock;
/**
* 公平锁
* @author Administrator
*
*/
public class Demo9_Run {
public static void main(String[] args) {
//公平锁
//final Demo9Service service = new Demo9Service(true);
//非公平锁
final Demo9Service service = new Demo9Service(false);
Runnable runnalbe = new Runnable() {
@Override
public void run() {
System.out.println("#线程" + Thread.currentThread().getName() + "运行了");
service.serviceMethod();
}
};
Thread[] threadArray = new Thread[20];
for (int i = 0; i < 20; i++) {
threadArray[i] = new Thread(runnalbe);
}
for (int i = 0; i < 20; i++) {
threadArray[i].start();
}
}
}
class Demo9Service {
private ReentrantLock lock;
public Demo9Service(boolean isFair) {
super();
lock = new ReentrantLock(isFair);
}
public void serviceMethod() {
try {
lock.lock();
System.out.println("ThreadName=" +
Thread.currentThread().getName() + "获得锁");
} finally {
lock.unlock();
}
}
}