線程同步 synchronized;
synchronized 使用時 主要用於同步代碼塊和同步方法;
同步代碼塊:
public void display(){
private count=200;
synchronized(this){
for(int i=0;i<count;i++){
system.out.println(i);
}
}
}
wait(), notify (),notifyAll();三個方法用在synchronized的同步代碼塊 或同步方法中 ,該三個方法必須和synchronized一起使用 否則報錯;
wait(); 當前線程 中斷,並釋放對象鎖;
notify();另外的線程執行某對象的notify();會喚醒此對象等待池中的某個線程
notifyAll();另外的線程執行某對象的notify();會喚醒此對象等待池中的所有線程
同步方法:
public synchronized void display(){
private count=200;
for(int i=0;i<count;i++){
system.out.println(i);
}
}