package pkg;
class A {
public synchronized void foo(B b) {
System.out.println("当前线程名: " + Thread.currentThread().getName()
+ " 进入了A实例的foo方法"); // ①
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
ex.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 bar(A a) {
System.out.println("当前线程名: " + Thread.currentThread().getName()
+ " 进入了B实例的bar方法"); // ②
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("当前线程名: " + Thread.currentThread().getName()
+ " 企图调用A实例的last方法"); // ④
a.last();
} public synchronized void last() {
System.out.println("进入了B类的last方法内部");
}
}public class DeadLock implements Runnable {
A a = new A();
B b = new B(); public void init() {
Thread.currentThread().setName("主线程");
// 调用a对象的foo方法
a.foo(b);
System.out.println("进入了主线程之后");
} public void run() {
Thread.currentThread().setName("副线程");
// 调用b对象的bar方法
b.bar(a);
System.out.println("进入了副线程之后");
} public static void main(String[] args) {
DeadLock dl = new DeadLock();
// 以dl为target启动新线程
new Thread(dl).start();
// 调用init()方法
dl.init();
}
}
运行结果:
当前线程名: 主线程 进入了A实例的foo方法
当前线程名: 副线程 进入了B实例的bar方法
当前线程名: 副线程 企图调用A实例的last方法
当前线程名: 主线程 企图调用B实例的last方法
提问:为什么先运行init方法,不是dl作为target传入start之后直接运行run方法么?
thread

解决方案 »

  1.   

    new Thread(dl).start();1)
    // 调用init()方法
    dl.init();2)
    代码太多了没详细看,没理解错的话,楼主问的是为什么先执行2,不是1吧,简单来说,就是start方法表示启动新线程,新线程的创建跟执行需要花费时间,虽然很小,这个过程中主线程会继续执行下面的语句,这个耗时少更快,所以2)先执行。