public class Number { //volatile修饰词,变量值发生改变对其他线程可见,可以保证可见性, //有序性,不保证原子性 /* * 1、创建性 * 2、有序性 * 3、原子性 * synchronized关键性、保证原子性、保证有序性 * */ // private volatile int i; private int i; public void incr(){ synchronized (this){ i++; } } public int getI() { return i; } public void setI(int i) { this.i = i; } }
测速代码:
public class NumberTest { public static void main(String[] args) { Number number = new Number(); for(int i = 0;i<10;i++){ new Thread(()->{ for (int j=0;j<10000;j++){ number.incr(); } }).start(); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //i++线程不安全 System.out.println(number.getI()); } }