关键字synchronized拥有锁重入的功能,也就是在使用synchronized时,当一个线程得到了一个对象的锁之后,再次请求此对象时是可以再次得到该对象的锁。
示例代码1:
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) {
final SyncDubbo1 sd = new SyncDubbo1();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
sd.method1();
}
});
t1.start();
}
}
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) {
final SyncDubbo1 sd = new SyncDubbo1();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
sd.method1();
}
});
t1.start();
}
}
结果:
示例代码2:
public class SyncDubbo2 {
static class Main {
public int i = 10;
public synchronized void operationSup() {
try {
i--;
System.out.println("Main print i=" + i);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class Sub extends Main {
public synchronized void operationSub() {
try {
while (i > 0) {
i--;
System.out.println("sub print i=" + i);
Thread.sleep(100);
this.operationSup();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
Sub sub = new Sub();
sub.operationSub();
}
});
t1.start();
}
}
运行结果:
出现异常,锁自动释放。对于一个web应用程序,异常释放锁的情况,如果不及时处理,很可能对你的应用程序业务逻辑产生严重错误,比如你现在执行一个队列任务,很多对象都去在等待第一个对象正确执行完毕再去释放锁,但是第一个对象由于异常的出现,导致业务逻辑没有正常执行完毕,就释放了锁,那么可想而知后续的对象执行的都是错误的逻辑。所以这一点一定要引起注意,在编写代码的时候,一定要考虑周全。
示例代码:
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");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("log info i=" + i);
// throw new RuntimeException();//程序遇到异常停止运行(1)
continue;//程序遇到异常之后,继续执行(2)
}
}
}
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();
}
}
// throw new RuntimeException();//程序遇到异常停止运行(1)
continue;//程序遇到异常之后,继续执行(2)
}
}
}
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();
}
}
运行结果(1):
运行结果(2):
在写一个存储过程时:
当我们使用了for循环,那么for循环里面一定要写的是begin。如果不写begin那么久不能在里面写exception。