类中同步方法被调用,其他方法是否可以同时被调用

毕业初期,面试时经常被问到一个问题:一个类中同步方法被调用时,它的其他方法是否可以同时被调用?记得当时看过面试宝典,答案是否,不能被调用。但是其实这个答案是错误的。
正确的回答应该是该类中其他同步方法不能被同时调用,但非同步方法可以被调用。下面给出例子。
Business.java

package thread;

public class Business
{

public synchronized void methodA() throws InterruptedException
{
Thread.sleep(10000);
System.out.println("I am method A, I am a synchronized method");
}

public void methodB()
{
System.out.println("I am not a synchronized method, check if i can be called when the a synchronized method are called");
}

public synchronized void methodC()
{
System.out.println("I am a synchronized method, check if i can be called when the a synchronized method are called");
}
}



Thread1.java

package thread;

public class Thread1 implements Runnable
{
private Business bus;
public Thread1(Business b)
{
this.bus = b;
}
@Override
public void run()
{
try
{
bus.methodA();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}



Thread2.java

package thread;

public class Thread2 implements Runnable
{
private Business bus;
public Thread2(Business b)
{
this.bus = b;
}
@Override
public void run()
{
bus.methodB();
}

}



thread3.java

package thread;

public class Thread3 implements Runnable
{
private Business bus;
public Thread3(Business b)
{
this.bus = b;
}
@Override
public void run()
{
bus.methodC();
}

}



TestMain.java

package thread;

public class TestMain
{

/**
* @param args
*/
public static void main(String[] args)
{
Business b = new Business();
Thread th1 = new Thread(new Thread1(b));
Thread th2 = new Thread(new Thread2(b));
Thread th3 = new Thread(new Thread3(b));
th1.start();
th2.start();
th3.start();
}

}



运行会发现methodB的会立即被执行,但是methodA会sleep 10s,然后跟着methodC执行。

其实很容易理解,用sychronized把methodA和methodC加锁,默认情况下sychronized是对当前class类对象加锁,相当于

public void methodA() throws InterruptedException
{
synchronized(this)
{
Thread.sleep(10000);
System.out.println("I am method A, I am a synchronized method");
}

}

public void methodC()
{
synchronized(this)
{
System.out.println("I am a synchronized method, check if i can be called when the a synchronized method are called");
}

}


所以当methodA持有锁时methodC就不能拿到锁,故不能被调用,而methodB则不需要获取锁,故可以被执行

你可能感兴趣的:(java基础)