1.synchronized 鎖 鎖定當前對象、線程。不讓其它線程進來。
用法 :
public void add(String name) {
synchronized (this){
num++;
try{
Thread.sleep(1);
} catch(InterruptedException e) {}
System.out.println(name+" 您是第" + num + "個");
}
}
或
public synchronized void add(String name) {
num++;
try{
Thread.sleep(1);
} catch(InterruptedException e) {}
System.out.println(name+" 您是第" + num + "個");
}