Java線程同步中的一個重要的概念synchronized.
synchronized是java的關鍵字,是一種同步鎖,它作用的對象有以下幾種:
①作用在代碼塊上.該代碼塊稱為同步代碼塊,作用范圍是大括號{..}括起來的代碼,作用的對象是調用這個代碼塊的對象
②方法上
③靜態方法
④類
案列1,同步代碼塊
```
public class MySynchornized implements Runnable {
private static int count;
public MySynchornized() {
count = 0;
}
@Override
public void run() {
// 同步代碼塊
synchronized (this) {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public int getCount() {
return count;
}
}
調用
測試結果:
未加鎖情況下:
加鎖: