/**
* @Description TODO
* @Author "zhouhai"
* @Date2018/10/721:21
**/
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();
}
}
method1..
method2..
method3..
重入锁
/**
* @Description TODO
* @Author "zhouhai"
* @Date2018/10/720:22
**/
public class SyncDubbo {
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();
}
}
Sub print i = 9
Main print i = 8
Sub print i = 7
Main print i = 6
Sub print i = 5
Main print i = 4
Sub print i = 3
Main print i = 2
Sub print i = 1
Main print i = 0
有继承关系的synchronized并不影响其使用,父子类一起同步保证其线程安全
/**
* @Description TODO
* @Author "zhouhai"
* @Date2018/10/721:03
**/
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);
}
}
}
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();
}
}
t1,i=1
t1,i=2
t1,i=3
t1,i=4
t1,i=5
t1,i=6
t1,i=7
t1,i=8
t1,i=9
t1,i=10
log info i = 10
java.lang.NumberFormatException: For input string: "a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at SyncException.operation(SyncException.java:17)
at SyncException$1.run(SyncException.java:32)
at java.lang.Thread.run(Thread.java:745)
t1,i=11
t1,i=12
t1,i=13
t1,i=14
同步锁遇到异常直接释放锁