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

出处:https://blog.csdn.net/iteye_2474/article/details/82512318

问题:一个类中同步方法被调用时,它的其他方法是否可以同时被调用?

正确的回答应该:是该类中其他同步方法不能被同时调用,但非同步方法可以被调用。下面给出例子。

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");
    }
}
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) {
            e.printStackTrace();
        }
    }

}
public class Thread2 implements Runnable{
    private Business bus;

    public Thread2(Business b) {
        this.bus = b;
    }

    @Override
    public void run() {
        bus.methodB();
    }
}
public class Thread3 implements Runnable {
    private Business bus;

    public Thread3(Business b) {
        this.bus = b;
    }

    @Override
    public void run() {
        bus.methodC();
    }
}
public class Test1 {

    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();
    }

}

结果console:

I am not a synchronized method, check if i can be called when the a synchronized method are called
I am method A, I am a synchronized method
I am a synchronized method, check if i can be called when the a synchronized method are called

运行会发现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则不需要获取锁,故可以被执行

猜你喜欢

转载自www.cnblogs.com/myseries/p/10673651.html