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 + "个");
}