/*
同步函數用的是哪一個鎖呢?
函數需要被對象調用。那麼函數都有一個所屬對象引用。就是this。
是以同步函數使用的鎖是this。
通過該程式進行驗證。
使用兩個線程來買票。
一個線程在同步代碼塊中。
一個線程在同步函數中。
都在執行買票動作。
如果在加上同步的情況下還出現0号票
說明使用的兩個線程使用的不是同一個鎖
如何找問題:
1,明确哪些代碼是多線程運作代碼。
2,明确共享資料。
3,明确多線程運作代碼中哪些語句是操作共享資料的。
*/
class Ticket implements Runnable
{
private int tick = 100;
Object obj = new Object();
boolean flag = true;
public void run()
{
if(flag)
{
while(true)
{
synchronized(this)//将鎖旗标由obj 改為this ,結果不出現0号票
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....code : "+ tick--);
}
}
}
}
else
while(true)
show();
}
public synchronized void show()//this
{
if(tick>0)
{
try{Thread.sleep(10);}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....show.... : "+ tick--);
}
}
}
class ThisLockDemo
{
public static void main(String[] args)
{
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try{Thread.sleep(10);}catch(Exception e){}
t.flag = false;
t2.start();
// Thread t3 = new Thread(t);
// Thread t4 = new Thread(t);
// t3.start();
// t4.start();
}
}