java 锁定对象,Java同步方法锁定对象或方法?

If I have 2 synchronized methods in the same class, but each accessing different variables, can 2 threads access those 2 methods at the same time? Does the lock occur on the object, or does it get as specific as the variables inside the synchronized method?

Example:

class X {

private int a;

private int b;

public synchronized void addA(){

a++;

}

public synchronized void addB(){

b++;

}

}

Can 2 threads access the same instance of class X performing x.addA() and x.addB() at the same time?

解决方案

If you declare the method as synchonized (as you're doing by typing public synchronized void addA()) you synchronize on the whole object, so two thread accessing a different variable from this same object would block each other anyway.

If you want to synchronize only on one variable at a time, so two threads won't block each other while accessing different variables, you have synchronize on them separately in synchronized () blocks. If a and b were object references you would use:

public void addA() {

synchronized( a ) {

a++;

}

}

public void addB() {

synchronized( b ) {

b++;

}

}

But since they're primitives you can't do this.

I would suggest you to use AtomicInteger instead:

import java.util.concurrent.atomic.AtomicInteger;

class X {

AtomicInteger a;

AtomicInteger b;

public void addA(){

a.incrementAndGet();

}

public void addB(){

b.incrementAndGet();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值