一个类里的两个synchronized方法

同一实例的两个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(); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值