JAva readにもロックが必要です

1595 ワード

今日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();ロックをかけると、さっき汚れたデータを読んだ問題は発生しません.