JAVA的synchronized關鍵字為線程加鎖,目的是保證數據執(zhí)行的一致性。
防止多個線程同時操作一個對象或者數據,造成數據混亂。
synchronized對象鎖示例
public class RunTest implements Runnable {
static RunTest rt = new RunTest();
static int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
// 對象鎖代碼塊形式
synchronized(this){ // 啟動后,線程執(zhí)行完畢后,再執(zhí)行下一個的順序執(zhí)行。
System.out.println(i + "-->" + Thread.currentThread().getName());
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i + "-->" + Thread.currentThread().getName() +" end");
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Thread t1 = new Thread(rt);
Thread t2 = new Thread(rt);
t1.start();
t2.start();
// t1.join();// 線程執(zhí)行完畢之后,才繼續(xù)執(zhí)行主程序內容。
// t2.join();
// 第二種方法,線程執(zhí)行完畢之后,才繼續(xù)執(zhí)行主程序內容。
while(t1.isAlive() || t2.isAlive()){
}
System.out.println("-->" + i);
}
}
執(zhí)行效果輸出
0-->Thread-0
0-->Thread-0 end
0-->Thread-1
0-->Thread-1 end
-->0