例のAtomicInteger

AtomicIntegerは、原子、可視性、秩序確保します

パブリック クラスAtomicIntegerTest { 
    
    プライベート 静的のAtomicInteger値=   新規のAtomicInteger()。

    パブリック 静的 ボイドメイン(文字列[]引数)が例外:InterruptedExceptionをスロー{ 

        スレッドT1 = 新しいスレッド(新しいLoopVolatile())。
        t1.start(); 

        スレッドT2 = 新しいスレッド(新しいLoopVolatile2()); 
        t2.start(); 

        t1.join(); 
        t2.join(); 
        システム。 .println(" 最後のvalがあります:" +値); // 20000 
    } 

    プライベート 静的 クラスLoopVolatile実装Runnableを{
         公共 ボイドラン(){
             長いヴァル= 0 一方、(ヴァル< 10000L ){ 
                value.getAndIncrement()。
                ヴァル ++ ; 
            } 
        } 
    } 

    プライベート 静的 クラスLoopVolatile2実装Runnableを{
         公共 ボイドラン(){
             長いヴァル= 0 同時に(ヴァル< 10000L ){ 
                value.getAndIncrement()。
                ヴァル ++ ; 
            } 
        } 
    } 
}

 

おすすめ

転載: www.cnblogs.com/moris5013/p/11823442.html