0.原子性操作
完整执行。原子性操作可以靠硬件实现,也可以靠软件实现。
1.多个间断的原子性操作,不能保证原子性
private static Vector<Integer> tickets = new Vector<>();static {for (int i = 0; i < 10000; i++) {tickets.add(i);}}public static void main(String[] args) {for (int i = 0; i < 10; i++) {new Thread(()->{while(tickets.size() > 0){try {TimeUnit.MILLISECONDS.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("销售票编号:" + tickets.remove(0));}}).start();}
首先Vector 的 size() 方法 和 remove 方法 都可以保证原子性。但是上面的逻辑不对。多个线程同时去排队判断 size >0 。于是又同时去排队执行 remove,就会导致
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 0
