同步函數和同步代碼塊的區別:
1. 同步函數的鎖是固定的this。
2. 同步代碼塊的鎖是任意的對象。
建議使用同步代碼塊。
因爲同步函數的鎖是固定的this,同步代碼塊的鎖是任意的對象,那麼若是同步函數和同步代碼塊都使用this
做爲鎖,就能夠實現同步。
java
class Ticket implements Runnable { private int num = 100; // Object obj = new Object(); boolean flag = true; public void run() { // System.out.println("this:"+this); if(flag) while(true) { synchronized(this) { if(num>0) { try{Thread.sleep(10);}catch (InterruptedException e){} System.out.println(Thread.currentThread().getName()+".....obj...."+num--); } } } else while(true) this.show(); } public synchronized void show() { if(num>0) { try{Thread.sleep(10);}catch (InterruptedException e){} System.out.println(Thread.currentThread().getName()+".....function...."+num--); } } } class SynFunctionLockDemo { public static void main(String[] args) { Ticket t = new Ticket(); // System.out.println("t:"+t); Thread t1 = new Thread(t); Thread t2 = new Thread(t); t1.start(); try{Thread.sleep(10);}catch(InterruptedException e){} t.flag = false; t2.start(); } }