1. 程式人生 > >java-同步函式的鎖是this

java-同步函式的鎖是this

/* 同步函式用的是哪一個鎖呢?
 * 函式需要被物件呼叫,那麼函式都有一個所屬物件引用,就是this
 * 所以同步函式使用的鎖都是this,通過該程式進行驗證
 * 使用兩個執行緒來賣票:一個執行緒在同步程式碼塊中,一個執行緒在同步函式中.都在執行賣票成
 * */
public class ThisLockDemo {
	public static void main(String[] args) {
		Ticke t = new Ticke();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		t1.start();
		try {
			Thread.sleep(10);
		} catch (Exception e) {}
		t.flag = false;
		t2.start();
	}
}
class Ticke implements Runnable {
	private int tick = 100;
	Object obj = new Object();
	boolean flag = true;
	public void run() {
		if (flag) {
			while (true) {
				synchronized (this) {
					if (tick > 0) {
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						System.out.println(Thread.currentThread().getName()
								+ "...code :" + tick--);
					}
				}
			}
		} else
			while (true)
				show();
	}
	public synchronized void show() {
		if (tick > 0) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName() + "sale:"+ tick--);
		}
	}
}