i++ 線程不安全示例
public class TestAtomicInteger{
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<1000;i++){
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<100;j++){
count++;
}
}
}).start();
}
Thread.sleep(5*1000);
System.out.println(count);
}
}
輸出截圖:

result.png
AtomicInteger解決線程安全問題
public class TestAtomicInteger{
private static AtomicInteger count= new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<10000;i++){
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<1000;j++){
count.getAndIncrement();
}
}
}).start();
}
Thread.sleep(5*1000);
System.out.println(count);
}
}
輸出截圖:

result.png
思考為什么?
第一種寫法報(bào)錯(cuò),第二種沒有問題
//第一種, idea提示錯(cuò)誤
public class TestAtomicInteger{
public static void main(String[] args) throws InterruptedException {
int count = 0;
for(int i=0;i<1000;i++){
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<100;j++){
count++; //錯(cuò)誤提示:Variable 'count' is accessed from within inner class, needs to be final or effectively final
}
}
}).start();
}
Thread.sleep(5*1000);
System.out.println(count);
}
}
//第二種, 運(yùn)行結(jié)果正常
public class TestAtomicInteger{
public static void main(String[] args) throws InterruptedException {
AtomicInteger count= new AtomicInteger(0);
for(int i=0;i<10000;i++){
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<1000;j++){
count.getAndIncrement();
}
}
}).start();
}
Thread.sleep(5*1000);
System.out.println(count);
}
}
個(gè)人理解第一種為值傳遞,第二種為引用傳遞;具體不是很清晰,大概感覺是這么個(gè)原因