同步函數(shù)的鎖是固定的this.
同步代碼塊的鎖是任意的對(duì)象。
建議使用同步代碼塊。
因?yàn)橥胶瘮?shù)的鎖唯一的,只能是this
當(dāng)同步代碼塊的鎖是this時(shí),可以簡(jiǎn)寫成同步函數(shù)。
package day12;
/*
同步函數(shù)使用的鎖是this;
同步函數(shù)和同步代碼塊的區(qū)別:
同步函數(shù)的鎖是固定的this.
同步代碼塊的鎖是任意的對(duì)象。
建議使用同步代碼塊。
因?yàn)橥胶瘮?shù)的鎖唯一的,只能是this
當(dāng)同步代碼塊的鎖是this時(shí),可以簡(jiǎn)寫成同步函數(shù)。
*/
class Ticket implements Runnable{ //extends Thread{
private int num = 400;
// 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) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"...obj..."+num--);
}
}
}
else
while (true)
show();
}
public synchronized void show(){
if(num>0){
try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
System.out.println(Thread.currentThread().getName()+"...function..."+num--);
}
}
}
public class SynFunctionLockDemo {
public static void main(String[] args) {
Ticket t = new Ticket();//創(chuàng)建一個(gè)線程任務(wù)對(duì)象。
System.out.println("t:"+t);
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
t.flag = false;
t2.start();
}
}