JAVA的synchronized關(guān)鍵字為線程加鎖,目的是保證數(shù)據(jù)執(zhí)行的一致性。
防止多個(gè)線程同時(shí)操作一個(gè)對(duì)象或者數(shù)據(jù),造成數(shù)據(jù)混亂揩局。
synchronized對(duì)象鎖示例
public class RunTest implements Runnable {
static RunTest rt = new RunTest();
static int i = 0;
@Override
public void run() {
// TODO Auto-generated method stub
// 對(duì)象鎖代碼塊形式
synchronized(this){ // 啟動(dòng)后,線程執(zhí)行完畢后掀虎,再執(zhí)行下一個(gè)的順序執(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í)行主程序內(nèi)容涩盾。
// t2.join();
// 第二種方法十气,線程執(zhí)行完畢之后,才繼續(xù)執(zhí)行主程序內(nèi)容春霍。
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