ReentrantLock
重入锁,在需要进行代码同步部分上加锁,但是一定要记得解锁。
类型:公平锁(队列方式进行排队)、非公平锁(按照cpu的分配),非公平锁性能要比公平锁性能高,默认为非公平锁。
package dmeo9;
import javax.security.auth.login.FailedLoginException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Created by liudan on 2017/8/4.
*/
public class DemoLock {
private Lock lock = new ReentrantLock(false);
public void m1(){
try {
lock.lock();
System.err.println(Thread.currentThread().getName()+":线程,进入m1");
Thread.sleep(3000);
System.err.println(Thread.currentThread().getName()+":线程,继续执行 m1");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
-
lock.unlock();//解锁的动作写在
finally内较好,因为解锁锁程序可能会发生一些意想不到的错误,导致无法正常解锁
}
}
public void m2(){
try {
lock.lock();
System.err.println(Thread.currentThread().getName()+":线程,进入m2");
Thread.sleep(3000);
System.err.println(Thread.currentThread().getName()+":线程,继续执行 m2");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public static void main(String[] atgs){
final DemoLock demoLock = new DemoLock();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
demoLock.m1();
demoLock.m2();
}
},"t_00001");
t1.start();
}
}
输出:
t_00001:线程,进入m1
t_00001:线程,继续执行 m1
t_00001:线程,进入m2
t_00001:线程,继续执行 m2