Synchronized的幾種用法:
1.鎖對象的整個方法:
public synchronized void test() {
System.out.println("鎖對象的整個方法");
}
public void test1() {
synchronized(this) {
System.out.println("2. 鎖對象方法的部分代碼");
}
}
3.鎖類的整個方法:
public static synchronized void test2() {
System.out.println("鎖類的整個方法");
}
4.鎖類的方法的部分代碼:
public static void test3() {
synchronized(SynchronizedTest.class) {
System.out.println("鎖類的方法的部分代碼");
}
}
5.鎖特定對象的代碼:
private Object obj = new Object();
public void test4() {
synchronized(obj) {
System.out.println("鎖特定對象的代碼");
}
}
以上就是synchronized的幾種用法,我們在實際開發中可以有選擇的使用。