package com.tl.executor.locks;
public class Sync02 implements Runnable{
static volatile int i=0;
@Override
public void run() {
for (int j=0;j<100000;j++){
add();
System.out.println(Thread.currentThread().getName()+"||||||||"+i);
}
}
public static void add(){
i++;
}
public static void main(String[] args) throws InterruptedException {
Sync02 sync02= new Sync02();
Thread thread1=new Thread(sync02);
Thread thread2=new Thread(sync02);
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(i);
}
}
/*****
Thread-0||||||||196669
Thread-0||||||||196670
Thread-1||||||||196655
Thread-1||||||||196672
Thread-1||||||||199994
Thread-1||||||||199995
Thread-1||||||||199996
Thread-1||||||||199997
Thread-1||||||||199998
Thread-1||||||||199999
Thread-1||||||||200000
200000
*/
作爲對比的是
Thread多線程進行不加鎖控制執行順序適用volatile關鍵字,不能保證執行結果的原子性,本地加載的無序發生爭搶導致
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.