解决方法
1、 使用循环CAS,实现i++原子操作
jdk1.5后java.util.concurrent.atomic包提供了常用的原子操作
1,volatile 保证内存可见性
2,CAS:保证数据原子性 unsafe
public class AtomicDemo {
static AtomicInteger a = new AtomicInteger(0);
public static void main(String[] args) {
for(int i=0;i<10;i++){
Thread thread = new Thread(()->{
for(int j=0;j<10000;j++){
a.getAndIncrement();
}
System.out.println(a);
});
thread.start();
}
}
}
2、使用synchronized,实现i++原子操作
public class SynPlusDemo {
private static int s=0;
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<10;i++){
Thread thread = new Thread(()->{
for(int j=0;j<10000;j++){
synchronized (SynPlusDemo.class){
s++;
}
}
});
thread.start();
}
Thread.sleep(3000);
System.out.println(s);
}
}
3、join可以阻塞主线程,所以必须等待该线程执行结束后才开启下一个线程
public class JoinDemo {
private static int s=0;
public static void main(String[] args) throws InterruptedException {
for (int j=0;j<100;j++){
Thread thread = new Thread(()->{
for (int k=0;k<1000;k++){
s++;
}
},"thread-"+j);
thread.start();
// join可以阻塞主线程,所以必须等待该线程执行结束后才开启下一个线程
thread.join();
}
System.out.println(s);
}
}