十分钟搞定大厂java面试必问并发的基石CAS
Cas也是线程同步的一种解决方案,很多人区分不清楚它和synchronized。先看下这段代码:public class MyCas { private static int num = 0; public stati
Cas也是线程同步的一种解决方案,很多人区分不清楚它和synchronized。
先看下这段代码:
public class MyCas {
private static int num = 0;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i1 = 0; i1 < 1000; i1++) {
num++;
}
}
}).start();
}
Thread.sleep(3000);
System.out.println(num);
}}创建了两个线程每个线程对num进行了1000次加1操作,打印出来的结果是多少呢?
了解线程同步的同学应该知道这段代码是线程不安全的结果不一定是2000,而是小于等于2000。
如果想让它变得线程安全可以在num++这里加上“synchronized”关键字:
for(int i1=0;i1< 1000;i1++){synchronized (MyCas.class){
num++;
}}问题是解决了,但是我们知道加了synchronized关键字,一次只允许一个线程执行num++的代码,其它线程会被阻塞,之后被唤醒,比较影响性能。
有没有其它方法来解决这个问题呢?
public class MyCas {
private static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable()原创不易,完成人机校验,阅读全文