死锁程序:
class A{
public synchronized void foo(B b){
System.out.println("当前线程名称:"+Thread.currentThread().getName()+"进入A实例的foo方法");
try{
sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("当前线程名称:"+Thread.currentThread().getName()+"企图调用B实例的last方法");
b.last();
}
public synchronized void last(){
System.out.println("进入了A类的last方法内部");
}
}
class B{
public synchronized void info(A a){
System.out.println("当前线程名称:"+Thread.currentThread().getName()+"进入B实例的info方法");
try{
sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("当前类的名称:"+Thread.currentThread().getName()+"企图调用A类的last方法");
a.last();
}
public synchronized void last(){
System.out.println("进入了B类的方法内部");
}
}
public class Sisuocx implements Runnable{
A a = new A();
B b = new B();
public void init(){
currentThread().setName("主线程");
//调用a对象的foo方法
a.foo(b);
System.out.println("进入了主线程之后");
}
public void run(){
currentThread().setName("副线程");
//调用b对象的info方法
b.info(a);
System.out.println("进入了副线程之后");
}
public static void main(String[] args) {
Sisuocx s = new Sisuocx();
//启动新线程
new Thread(s).start();
//调用init()方法
s.init();
}
}
死锁程序讲解:
上面程序中A对象和B对象的方法中都是同步方法,也就是A对象和B对象都是同步死锁。程序中两个线程执行,一个线程的线程执行体是Sisuocx的init()方法,另一个线程的线程执行体是Sisuocx的run()方法(主线程调用了init()方法)。其中run()方法中让B对象调用info()方法,而init()方法让A对象调用foo()方法,调用了A对象的foo()方法,进入foo()方法之前,该线程对A对象加锁,随后让主线程暂停100毫秒;CUP切换到执行另一个线程,让B对象执行info()方法,所以看到副线程开始执行B实例的info()方法,进入info()方法之前,该线程对B对象加锁,随后副线程也暂停100毫秒;接下来主线程会先醒过来,继续向下执行,直到希望调用B对象的last()方法,执行该方法之前必须先对B对象加锁,但此时副线程正保持着B对象的锁,所以主线程阻塞了;接下来副线程应该也醒过来了,继续向下执行,直到希望调用A对象的last()方法,执行该方法之前必须先对A对象加锁,但此时主线程正保持着A对象的锁,所以副线程阻塞了;至此就出现了主线程保持着A对象的锁,等待着B对象的锁,副线程保持着B对象的锁,等待着A对象的锁,两个线程相互等待对方先释放锁,所以就出现了死锁。