同一个对象中的一个synchronized方法如果已有一个线程进入,则其它的线程必须等该线程结束后才能进入该方法。那么,如果一个类中有多个synchronized方法,会有什么情况呢?
看下面一段代码:
public class Test { static Test t = new Test(); static Test2 t2 = new Test2(); public static void main(String[] args) { // TODO Auto-generated method stub TestThread tt = t.new TestThread(); tt.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } t2.test1(); } class TestThread extends Thread { @Override public void run() { // TODO Auto-generated method stub t2.test2(); } } } class Test2 { public synchronized void test1() { System.out.println("test1 called"); } public synchronized void test2() { System.out.println("test2 called"); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("test2 exit"); } }
运行结果如下:
test2 called test2 exit test1 called
很明显,当对象t2的synchronized方法test2被线程tt调用时,主线程也无法进入其test1方法,直到线程tt对test2方法的调用结束,主线程才能进入test1方法。
结论,对于synchronized方法,Java采用的是对象锁定的方式,当任何一个synchronized方法被访问的时候,该对象中的其它synchronized方法将全部不能被访问。
下一篇: Java牛角尖【010】: 当对象a.equals(b)时,a.hashCode == b.hashCode吗?