buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

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的一个数。

posted on 2020-01-07 18:56  buguge  阅读(81)  评论(0)    收藏  举报