Java內建鎖
阿新 • • 發佈:2018-12-12
啟動類
public class LockTest {
public static void main(String[] args) {
ObjLock test = new ObjLock();
for (int i = 0; i < 5; i++) {
Thread thread = new LockThread(test);
thread.start();
}
}
}
執行緒類
public class LockThread extends Thread { ObjLock lock; public LockThread(ObjLock lock) { this.lock = lock; } public void run() { lock.syncObjMethod1(); lock.syncObjMethod2(); lock.syncPriObjMethod(); ObjLock.syncClaMethod(); } /** * 私有鎖和物件鎖不會產生競爭 * synchronized加在方法上和synchronized(this)均是對當前物件加鎖,構成競爭關係同一時刻只能有一個方法能執行。 */ }
方法類
public class ObjLock {
/** 私有物件 */ private Object object = new Object(); /** * 物件鎖方法 */ public synchronized void syncObjMethod1() { System.out.println("Obj Lock 1 begin" + ", time = " + System.currentTimeMillis() + "ms"); try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Obj Lock 1 end"); } /** * 物件鎖(採用synchronized (this)) */ public void syncObjMethod2() { synchronized (this) { System.out.println("Obj Lock 2 begin" + ", time = " + System.currentTimeMillis() + "ms"); try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Obj Lock 2 end"); } } /** * 私有物件鎖 */ public void syncPriObjMethod() { synchronized (object) { System.out.println("Private Lock begin" + ", time = " + System.currentTimeMillis() + "ms"); try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Private Lock end"); } } // 用於Class類鎖計數 private static int claClockCount = 0; /** * 靜態同步方法呼叫的是Class物件鎖 */ public static synchronized void syncClaMethod() { System.out.println( "Class Lock begin claClockCount = " + claClockCount + ", time = " + System.currentTimeMillis() + "ms"); claClockCount++; try { Thread.sleep(2000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Class Lock end"); } }