注册 登录
编程论坛 JAVA论坛

一个关于死锁的问题

R的补 发布于 2019-03-26 15:36, 2439 次点击
class A
{
    public synchronized void foo(B b)
    {
        System.out.println("当前线程名:"+Thread.currentThread().getName()
                        +"进入了A的实例发foo方法");
        try
        {
            Thread.sleep(200);
        }
        catch(InterruptedException ie)
        {
            ie.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的实例发foo方法");
        try
        {
            Thread.sleep(200);
        }
        catch(InterruptedException ie)
        {
            ie.printStackTrace();
        }
        System.out.println("当前线程名:"+Thread.currentThread().getName()
                        +"尝试调用A实例的last()方法");
        a.last();
    }
    public synchronized void last()
    {
        System.out.println("进入了B类的last()方法");
    }
}
public class DeadLockDemo implements Runnable
{
    A a = new A();
    B b = new B();
    public void info()
    {
        Thread.currentThread().setName("主线程");
        a.foo(b);
        System.out.println("进入主线程之后");
    }
    @Override
    public void run()
    {
        Thread.currentThread().setName("副线程");
        b.bar(a);
        System.out.println("进入副线程之后");
    }
    public static void main(String[] args)
    {
        DeadLockDemo d = new DeadLockDemo();
        d.info();
        Thread t1 = new Thread(d);
        t1.start();
        /**
         *把d.info()放在前面就能正常运行
         *DeadLockDemo d = new DeadLockDemo();
         *d.info();
         *Thread t1 = new Thread(d);
         *t1.start();
         */
    }
}
4 回复
#2
R的补2019-03-26 15:39
我在编译的时候把main()方法中的d.info换一下位置变为
 public static void main(String[] args)
    {
        DeadLockDemo d = new DeadLockDemo();
        Thread t1 = new Thread(d);
        t1.start();
        d.info();
    }
就是死锁
但是前面发的程序就能正常运行
我就是把d.info()位置换一下为什么一个能正常运行。另一个却是死锁
#3
rind2019-03-26 16:30
回复 2楼 R的补
d.info()
放在前面是多线程顺序执行,顺序和使用单线程没多大区别。
main
|
|d.info()
|
|——————————new thread
|(无重要代码)             |
                                  |d.run()
                                  |

放在后面就是这样:
main
|
|————————————new thread
|                                    |
|d.info()                       |d.run()
|                                    |


两个方法的大概流程是:
I:1、获得a的锁,2、获得b的锁,3、释放b的锁,4、释放a的锁。
II、1、获得b的锁,2、获得a的锁,3、释放a的锁,4、释放b的锁。

死锁的原因就是:Thread.sleep(200)让两个线程的生存周期有交集。主要是I.1-I.2和II.1-II.2
#4
R的补2019-03-26 16:46
回复 3楼 rind
又是大佬帮忙回答的,感谢大佬!版主投票我有投你哈!
#5
rind2019-03-26 17:01
回复 4楼 R的补
没什么,只不过刚好是我知道的。
仅供参考,欢迎指正
1