/*
死锁:产生死锁的原因之一 同步的嵌套
本应该无限打印 但死锁会停止打印
*/
class Test implements Runnable{
boolean flag=true;
Test(boolean flag) {
this.flag=flag;
}
public void run(){
if(flag){
while(true){
synchronized(MyLock.locka){
System.out.println("if----locka");
synchronized(MyLock.lockb){
System.out.println("if----lockb");
}
}
}
}
else{
while(true){
synchronized(MyLock.lockb){
System.out.println("else----lockb");
synchronized(MyLock.locka){
System.out.println("else----locka");
}
}
}
}
}
}
class MyLock{
public static final Object locka=new Object();
public static final Object lockb=new Object();
}
class DeadLockTest{
public static void main(String[] args) {
Test a=new Test(true);
Thread t1=new Thread(a);
Thread t2=new Thread(a);
t1.start();
try{
Thread.sleep(100);
}
catch(InterruptedException e){
}
a.flag=false;
t2.start();
}
}
Java 死锁例子
最新推荐文章于 2024-10-10 23:21:50 发布