同一实例的两个synchronized方法不可以被两个线程同时访问,因为对象锁被占用。
也就是说,同一时刻,同一实例(注意,不是同一个类)的多个synchronized方法最多只能有一个被访问。
实例代码如下:
public class TwoSynchronizedMethodInOneClassTest {
private static int counter = 0;
public synchronized void a() {
while(true) { // Once this method is called by a thread, it will hold the lock, and not give way to other access thead.
System.out.println("AA---" + counter++);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void b() {
while(true) {
System.out.println("---BB" + counter++);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// single instance will use the same lock object.
public static TwoSynchronizedMethodInOneClassTest instance = new TwoSynchronizedMethodInOneClassTest();
public static void main(String[] args) {
Thread a = new Thread() {
public void run() {
TwoSynchronizedMethodInOneClassTest.instance.a();
}
};
Thread b = new Thread() {
public void run() {
TwoSynchronizedMethodInOneClassTest.instance.b(); // The same lock will not trun to state of idel, can method b() can never be accessed.
// new T().b(); // new T() will ues a different lock object, so method b() can be accessed.
}
};
a.start();
b.start();
}
}
一个类里的两个synchronized方法
最新推荐文章于 2022-07-20 23:29:10 发布
本文通过示例代码展示了在Java中,同一实例的两个synchronized方法不能被不同线程同时访问的原因。这是因为这些方法会使用相同的对象锁,一旦某个线程获取了锁,其他线程必须等待该锁被释放。
9884

被折叠的 条评论
为什么被折叠?



