并发编程的三大特性

  • 原子性

一个具有原子性的操作要么全部执行,要么不执行。具体来说,原子性的操作执行到一半,并不会因为CPU线程调度而被打断,这样的操作就是原子性操作。在Java并发编程中,synchronized关键字可以保证操作的原子性。

public class Atomicity {

    //volatile保证有序性和可见性
    static volatile int num = 0;

    //结果小于100000
    /*public static void incre() {
        num++;
    }*/

    //结果等于100000
    public synchronized static void incre() {
        //num++ 等于 num=num+1; 这个操作并不是一个原子操作,它会因为线程调度而被打断
        //需要家synchronized来保证原子性
        num++;
    }

    public static void main(String[] args) throws InterruptedException {

        Thread[] arrThread = new Thread[10];

        for(int i = 0; i<arrThread.length; i++) {
            arrThread[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    for(int j = 0; j<10000; j++) {
                        incre();
                    }
                }
            });
            arrThread[i].start();
        }

        for(Thread t : arrThread) {
            t.join();//等每个线程执行完
        }

        System.out.println("num ="+num);

    }

}
  • 可见性

程序在多线程下,其中一个线程修改线程之间的共享变量的值时,其它线程是会感知得道的,并且会把新的共享变量值以极短的时间同步到其它线程中。在Java中,volatile关键字可以保证操作的可见性。

public class Visibility {

    //结果是 start -> assign -> complete -> 死循环
    //static boolean initFlag = false;

    //结果是 start -> assign -> complete -> end
    //加了volatile关键字使得initFlag变量的更改对其它线程可见
    static volatile boolean initFlag = false;

    public static void main(String[] args) throws InterruptedException {

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("=========start");
                while(!initFlag) {

                }
                System.out.println("=========end");
            }
        }).start();

        Thread.sleep(2000);

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("=========assign");
                initFlag = true;
                System.out.println("=========complete");
            }
        }).start();

    }

}
  • 有序性

程序在多线程下,程序中代码执行的顺序是代码的先后执行的。程序代码不会因为指令重排序(程序为了优化执行效率从而打乱了代码的执行顺序)而打乱,从而导致程序产生不同的结果。在Java中同样,volatile关键字也可以保证操作的有序性。

import java.util.HashMap;
import java.util.HashSet;

public class Ordering {
    //运行到后面的结果:[a=0,b=0, a=1,b=0, a=0,b=1]
    //volatile保证了x、y赋值时的先后顺序
    static volatile int x = 0, y = 0;

    //运行到后面的结果:[a=0,b=0, a=1,b=0, a=0,b=1, a=1,b=1]
    //因为指令重排序,代码的执行顺序出现了 2、4操作 在 1、3的前面,例如2413,4213
    //static int x = 0, y = 0;

    public static void main(String[] args) throws InterruptedException {

        HashSet<String> hashSet = new HashSet<>();
        HashMap<String,Integer> hashMap = new HashMap<>();

        for (int i = 0; i<1000000; i++) {
            x = 0; y = 0;
            hashMap.clear();
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    int a = x; //1
                    y = 1; //2
                    hashMap.put("a",a);
                }
            });

            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    int b = y; //3
                    x = 1; //4
                    hashMap.put("b",b);
                }
            });

            thread1.start();
            thread2.start();
            thread1.join();
            thread2.join();

            hashSet.add("a="+hashMap.get("a")+",b="+hashMap.get("b"));
            System.out.println(hashSet);

        }

    }

}
  • 结束语

这篇博客只停留在使用层面,其中还有很多原理性的东西,包括Java线程内存模型、volatile的底层实现原理、synchronized的底层实现原理、指令重排等等,这些都没讲,感兴趣的小伙伴可以关注我以后的文章。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容