此代码中没有发生死锁错误?

时间:2014-05-26 16:21:12

标签: java multithreading java-ee

看看这段代码。当一个线程获取对象x中的synchronized方法而另一个线程获取对象y上的synchronized方法时,x不能调用对象y上的synchronized方法。并且不能在x上调用sync方法。这是我在书中学到的理论。现在看看这段代码

import java.io.*;

class classx
{
    synchronized void method_on_x()
    {
        System.out.println("method on class x");
    }
}

class classy
{
    synchronized void method_on_y()
    {
        System.out.println("method on class y");
    }
}

class accessx implements Runnable
{
    classx cx1;
    classy cy1;
    Thread t;

    public accessx(classx cx, classy cy)
    {
        t = new Thread(this);
        cx1 = cx;
        cy1 = cy;
        t.start();
    }

    public void run()
    {
        cx1.method_on_x();
        cy1.method_on_y();
    }
}

class accessy implements Runnable
{
    classx cx1;
    classy cy1;
    Thread t;

    public accessy(classx cx, classy cy)
    {
        t = new Thread(this);
        cx1 = cx;
        cy1 = cy;
        t.start();
    }

    public void run()
    {
        cy1.method_on_y();
        cx1.method_on_x();
    }
}

class multizync
{
    public static void main(String args[])
    {
        classx c1 = new classx();
        classy c2 = new classy();
        accessx a1 = new accessx(c1, c2);
        accessy a2 = new accessy(c1, c2);
        try
        {
            a1.t.join();
            a2.t.join();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        System.out.println("mAIN tHREAD eXECUTION cOMPLETED");
    }
}

这段代码创建了两个线程类accessx和accessy,它们在自己的实例上调用两个同步的方法。它可以发生。当accessx线程有

synchronized method_on_x 

它不能打电话

synchronized method_on_y 

哪个accessy不是它。那么为什么我不会得到错误。

1 个答案:

答案 0 :(得分:0)

您的代码中没有任何死锁情况:

  • a1按顺序调用method_on_x和method_on_y
  • a2依次调用method_on_y和method_on_x

是的,a1和a2在两个不同的线程中运行,他们可以等待对同步方法的访问,但只有很短的时间,因为只要"打印"操作完成后,该方法可用于来自另一个线程的调用。

相关问题