synchronized与volatile
public class TestMain { public volatile int i = 0; // public int getI() { // return i; // } // // public void setI(int i) { // this.i = i; // } public synchronized void inc(){ i++; } public static void main(String[] args) throws Throwable { TestMain testMain = new TestMain(); Runnable runnable = new Runnable() { @Override public void run() { long start = System.currentTimeMillis(); // while (true) { // testMain.inc(); //// testMain.setI(testMain.getI() + 1); // if (System.currentTimeMillis()-start > 2000) { // break; // } // } for (int j=0;j<10000;j++){ testMain.inc(); } System.out.println(Thread.currentThread().getId() + "/" + Thread.currentThread().getName() + ":" + testMain.i); } }; for (int i = 0; i < 5; i++) { new Thread(runnable).start(); } Thread.sleep(3000); System.out.println(Thread.currentThread().getId() + "/" + Thread.currentThread().getName() + ":" + testMain.i); } }
inc方法,加synchronized,则保证最终结果是50000。不加synchronized,则结果可能是小于50000的一个数。
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/articles/12163227.html