java read也需要加锁

今天被问到read需不需要加锁,结果没答上来。自己写了一个程序试了一下,答案是肯定的,read加锁是为了保证执行的顺序,让线程不会读到脏数据。

public class TestThread {
private int a = 1;

public synchronized void add(){
this.a = this.a + 1;
System.out.println(Thread.currentThread().getName() + "current a is " + a);
}

public int get(){
System.out.println("current a is " + a);
return a;
}

public static void main(String[] args) throws Exception{
final TestThread testThread = new TestThread();
Thread t1 = new Thread(new Runnable(){
public void run(){
testThread.add();
//make sure the second thread to be executed at this moment
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

testThread.get();
}
}
);

Thread t2 = new Thread(new Runnable(){
public void run(){
//make sure the first thread to be started firstly at beginning
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
testThread.add();
testThread.get();
}
}
);

t1.start();
t2.start();
}
}


output:
Thread-0current a is 2
Thread-1current a is 3
current a is 3
current a is 3

如果对testThread.add();testThread.get();加锁就不会出现刚才读到脏数据的问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值