当一个线程进入一个对象的一个synchronized()方法后,其他线程是否可进入此对象的其他方法?

来源:互联网 发布:apache日志 400 编辑:程序博客网 时间:2024/05/22 15:03

一个线程进入一个对象的synchronized()方法后,其他线程是否可以进入此对象的其他方法取决于方法本身,如果该方法是非synchronized()方法,那么是可以访问的,如果是synchronized()方法,那么不能访问。示例如下:

package synchLockTest;class Test{public synchronized void synchronizedMethod(){System.out.println("begin calling sychronizedMethod...");try{Thread.sleep(10000);}catch(InterruptedException e){e.printStackTrace();}System.out.println("finish calling  sychronizedMethod...");}public void generalMethod(){System.out.println("call generalMethod...");}}public class MultiThread {static final Test t=new Test();public static void main(String[] args) {Thread t1=new Thread(){public void run(){t.synchronizedMethod();}};Thread t2=new Thread(){public void run(){t.generalMethod();}};t1.start();t2.start();}}



输出:
begin calling sychronizedMethod...
call generalMethod...
finish calling  sychronizedMethod...

从上例可以看出,线程t1在调用synchronized()方法的过程中,线程t2仍然可以访问同一个对象的非sychronized()方法。

若将代码稍稍做改动:
在方法generalMethod()前加一个synchronized的修饰符。因为线程t1调用synchronized void synchronizedMethod()的时候(即线程t1获得了对象锁),t2是无法调用该方法的。修改后的代码如下:
package synchLockTest;class Test{public synchronized void synchronizedMethod(){System.out.println("begin calling sychronizedMethod...");try{Thread.sleep(10000);}catch(InterruptedException e){e.printStackTrace();}System.out.println("finish calling  sychronizedMethod...");}public synchronized void generalMethod(){System.out.println("call generalMethod...");}}public class MultiThread {static final Test t=new Test();public static void main(String[] args) {Thread t1=new Thread(){public void run(){t.synchronizedMethod();}};Thread t2=new Thread(){public void run(){t.generalMethod();}};t1.start();t2.start();}}
结果如下:
begin calling sychronizedMethod...
finish calling  sychronizedMethod...
call generalMethod...

如果其他方法是静态的方法,它用的同步锁是当前类的字节码,与非静态的方法不能同步,因此,静态方法可以被调用,实例如下:
package synchLockTest;class Test{public synchronized void synchronizedMethod(){System.out.println("begin calling sychronizedMethod...");try{Thread.sleep(10000);}catch(InterruptedException e){e.printStackTrace();}System.out.println("finish calling  sychronizedMethod...");}public synchronized static void generalMethod(){System.out.println("call generalMethod...");}}public class MultiThread {static final Test t=new Test();public static void main(String[] args) {Thread t1=new Thread(){public void run(){t.synchronizedMethod();}};Thread t2=new Thread(){public void run(){t.generalMethod();}};t1.start();t2.start();}}

结果如下:
begin calling sychronizedMethod...
call generalMethod...
finish calling  sychronizedMethod...


























0 0
原创粉丝点击