java多线程编程(四)——ReentrantLock锁
在JDK1.5中新增了Lock接口用来实现锁的功能,它提供了比synchroinzed关键字更强大的功能。
本文主要介绍常用的实现类ReentrantLock锁
ReentrantLock默认实现的是非公平锁,当然也可以通过传递参数true实现公平锁,源码如下
/**
* Creates an instance of {@code ReentrantLock}.
* This is equivalent to using {@code ReentrantLock(false)}.
*/
public ReentrantLock() {
sync = new NonfairSync();
}
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
我们看个ReentrantLock实现非公平锁示例
package com.example.demo.threadTest;
import java.util.concurrent.locks.ReentrantLock;
public class MyThread extends Thread{
FairLock fairLock=new FairLock();
@Override
public void run(){
System.out.println("线程:" + Thread.currentThread().getName());
fairLock.test();
}
public static void main(String[] args){
MyThread myThread1=new MyThread();
MyThread myThread2=new MyThread();
MyThread myThread3=new MyThread();
MyThread myThread4=new MyThread();
MyThread myThread5=new MyThread();
myThread1.start();
myThread2.start();
myThread3.start();
myThread4.start();
myThread5.start();
}
}
class FairLock{
ReentrantLock lock=new ReentrantLock(false);
public void test(){
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+"获取到锁");
} finally {
lock.unlock();
}
}
}
运行结果如下
线程:Thread-2
线程:Thread-1
Thread-1获取到锁
线程:Thread-0
Thread-0获取到锁
线程:Thread-3
Thread-3获取到锁
线程:Thread-4
Thread-4获取到锁
Thread-2获取到锁
可以看出此时执行顺序并不是按照获取锁的顺序来执行的。
我们通过传递参数true实现公平锁再看下运行效果
package com.example.demo.threadTest;
import java.util.concurrent.locks.ReentrantLock;
public class MyThread extends Thread{
FairLock fairLock=new FairLock();
@Override
public void run(){
System.out.println("线程:" + Thread.currentThread().getName());
fairLock.test();
}
public static void main(String[] args){
MyThread myThread1=new MyThread();
MyThread myThread2=new MyThread();
MyThread myThread3=new MyThread();
MyThread myThread4=new MyThread();
MyThread myThread5=new MyThread();
myThread1.start();
myThread2.start();
myThread3.start();
myThread4.start();
myThread5.start();
}
}
class FairLock{
ReentrantLock lock=new ReentrantLock(true);
public void test(){
try {
lock.lock();
System.out.println(Thread.currentThread().getName()+"获取到锁");
} finally {
lock.unlock();
}
}
}
运行结果如下
线程:Thread-1
Thread-1获取到锁
线程:Thread-0
Thread-0获取到锁
线程:Thread-4
Thread-4获取到锁
线程:Thread-2
Thread-2获取到锁
线程:Thread-3
Thread-3获取到锁
可以看出此时执行顺序是按照获取锁的顺序来执行的。当起第一个线程获取锁之后,其他要获取锁的线程进行排队,当第一个线程将锁释放后,其他线程按照排队顺序来依次获取锁。
你想拥有什么,你就去追求什么!