package cn.limbo.thread.Fair_noFair_test;
import java.util.concurrent.locks.ReentrantLock;
public class Service {
private ReentrantLock lock;
public Service(boolean isFair) {
super();
lock = new ReentrantLock(isFair);
}
public void serviceMethod() {
try {
lock.lock();
System.out.println(" ThreadName= " + Thread.currentThread().getName() + " 获得锁定");
} finally {
lock.unlock();
}
}
}
class RunFair {
public static void main(String[] args) {
Service service = new Service(true);
Runnable runable = 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(runable);
}
for (int i = 0; i < 10; i++) {
threads[i].start();
}
//先启动的线程首先获取到锁 (基本都是一致的)
}
}
class RunNotFair {
public static void main(String[] args) {
Service service = new Service(false);
Runnable runable = 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(runable);
}
for (int i = 0; i < 10; i++) {
threads[i].start();
}
//基本都不是一致的
}
}
公平锁和非公平锁(demo)
猜你喜欢
转载自blog.csdn.net/arcprodrelhh/article/details/78831709
今日推荐
周排行