public class ReentrantLockDemo {
//可重入的锁,公平模式,解决饥饿现象。
//最先等待的线程,一直不能获取资源来执行任务,则为饥饿现象。
private static Lock lock = new ReentrantLock2(true);
public static void main(String[] args) {
int num = 5;
ExecutorService executorService = Executors.newFixedThreadPool(num);
for (int i = 0; i < num; i++) {
executorService.execute(new testThread());
}
}
private static class testThread implements Runnable {
public void run() {
try {
lock.lock();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "." + ((ReentrantLock2)lock).getQueuedThreads());
}finally {
lock.unlock();
}
}
}
private static class ReentrantLock2 extends ReentrantLock {
private boolean fair;
public ReentrantLock2(boolean fair){
this.fair = fair;
}
@Override
public Collection<Thread> getQueuedThreads(){
List<Thread> threadList = new ArrayList<Thread>(super.getQueuedThreads());
Collections.reverse(threadList);
return threadList;
}
}
}
05-30
915
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-01
07-01
07-01
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交