Java多线程可重入锁例子解析

时间:2022-11-18 20:09:34

“可重入锁”的概念是:自己可以再次获得自己的内部锁。比如有一条线程获得了某个对象的锁,此时这个对象还没有释放,当其再次想获得这个对象的锁的时候还是可以获得的,如果不可锁重入的话,就会造成死锁。

class sysTest{
synchronized void test1(String str){
System.out.println(str+"1");
test2(str);
System.out.println("end" + str);
} synchronized void test2(String str){
System.out.println(str+"2");
}
} class myThread extends Thread{
String str = null;
public myThread(String str) {
this.str = str;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
new sysTest().test1(str);
}
} public class synchronizedTest { public static void main(String[] args) {
// TODO Auto-generated method stub
myThread th1 = new myThread("1str");
myThread th2 = new myThread("2str");
th1.start();
th2.start();
} }

在加粗的sychronized在的时候结果会有下面,结果不唯一的:

1str1

2str1

1str2

2str2

end2str

end1str

在加粗的sychronized去掉的时候结果会有下面,结果唯一的:

1str1

1str2

end1str

2str1

2str2

end2str

在这里必须要认识到,加一个sychronized方法里调用sychronized方法会造成不同步,需要注意。原因是两个锁的问题,

这个时候使用可重入概念解决的话,就要使用对象锁,因为在sychronized()代码块中再次获得该锁就会可以得到:

class sysTest{
static Object object = new Object();
void test1(String str){
synchronized(object){
System.out.println(str+"1");
test2(str);
System.out.println("end" + str);
} } void test2(String str){
synchronized(object){
System.out.println(str+"2");
}
}
} class myThread extends Thread{
String str = null;
public myThread(String str) {
this.str = str;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
new sysTest().test1(str);
}
} public class synchronizedTest { public static void main(String[] args) {
// TODO Auto-generated method stub
myThread th1 = new myThread("1str");
myThread th2 = new myThread("2str");
th1.start();
th2.start();
} }
结果:
1str1
1str2
end1str
2str1
2str2
end2str