線程

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章