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);
}
}
输出截图:
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);
}
}
输出截图:
思考为什么?
第一种写法报错,第二种没有问题
//第一种, idea提示错误
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++; //错误提示:Variable 'count' is accessed from within inner class, needs to be final or effectively final
}
}
}).start();
}
Thread.sleep(5*1000);
System.out.println(count);
}
}
//第二种, 运行结果正常
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);
}
}
个人理解第一种为值传递,第二种为引用传递;具体不是很清晰,大概感觉是这么个原因