今天被问到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();加锁就不会出现刚才读到脏数据的问题。