1. synchronized锁重入:
关键字synchronized拥有锁重入的功能,也就是在使用synchronized时,当一个线程得到了一个对象的锁后,再次请求此对象时是可以再次得到该对象的锁。
2. 示例:【com.bjsxt.base.sync005】SyncDubbo1
public class SyncDubbo1 {
public synchronized void method1(){
System.out.println("method1……");
method2();
}
public synchronized void method2(){
System.out.println("method2……");
method3();
}
public synchronized void method3(){
System.out.println("method3……");
}
public static void main(String[] args){
SyncDubbo1 sd = new SyncDubbo1();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
sd.method1();
}
});
t1.start();
}
}
执行结果
3. 示例:【com.bjsxt.base.sync005】SyncDubbo2
public class SyncDubbo2 {
static class Main{
public int i = 10;
public synchronized void sup(){
try {
i--;
System.out.println("Main i = " + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Sub extends Main{
public synchronized void sub(){
try {
while(i > 0){
i--;
System.out.println("Sub i = " + i);
Thread.sleep(100);
sup();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
Sub sub = new Sub();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
sub.sub();
}
});
t1.start();
}
}
执行结果
4. 出现异常,锁自动释放
示例:【com.bjsxt.base.sync005】SyncException
public class SyncException {
private int i = 0;
public synchronized void operation(){
while(true){
try {
i++;
Thread.sleep(200);
System.out.println(Thread.currentThread().getName() + ", i = " + i);
if(i == 10){
Integer.parseInt("a");
//throw new RuntimeException();
}
} catch (Exception e) {//InterruptedException
e.printStackTrace();
System.out.println("log info i = " + i);
//throw new RuntimeException();
//continue;
}
}
}
public static void main(String[] args){
final SyncException se = new SyncException();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
se.operation();
}
},"t1");
t1.start();
}
}
5. 说明
对于web应用程序,异常释放锁的情况,如果不及时处理,很可能对你的应用程序业务逻辑产生严重的错误,比如你现在执行一个队列任务,很多对象都去在等待第一个对象正确执行完毕再去释放锁,但是第一个对象由于异常的出现,导致业务逻辑没有正常执行完毕,就释放了锁,那么可想而知后续的对象执行的都是错误的逻辑。所以这一点一定要引起注意,在编写代码的时候,一定要考虑周全。