以下寫法是錯誤的
import java.sql.Time;
import java.util.concurrent.TimeUnit;
public class SynLock {
public static volatile int i=0;
public static int geti(){
//有可能第二個線程在第一個線程取出舊的值和插入新的值期間會讀取這個值
//導致兩個線程讀取到了相同值,最後出現重複值
return i++;
}
public static void main(String[] args) throws InterruptedException{
while (true){
Thread thread=new Thread(()->{
System.out.println(SynLock.geti());;
});
thread.start();
}
}
}
以下爲驗證存在風險的結果,我將結果存入文件後以讀取的形式驗證是否有重複列
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class CheckSaftyFailer {
public static void main(String[] args) throws FileNotFoundException, IOException {
InputStreamReader in=new InputStreamReader(new FileInputStream("F:\\comysp\\src\\main\\java\\data.txt"));
BufferedReader bufferedInputStream=new BufferedReader(in);
String b;
Map test= new HashMap();
while ((b=bufferedInputStream.readLine())!=null){
if(test.get(b)!=null){
System.out.println(b);
}else {
test.put(b,b);
}
}
}
}