一些多執行緒的筆記

2021-09-01 10:29:45 字數 785 閱讀 2432

1. 保護方法原子性的同時,也要注意保護方法中使用到的變數。下面這段**是否一定安全?

public class counter 

public synchronized void add1()

//other method

}

不一定,如果在other method中也處理counter但是又沒有保護的情況下,會出現問題,例如

public class counter 

public synchronized void add1() catch(exception e)

counter = count + 1;

} public void add2()

}

執行以下**可以看到效果

public static void main(string args) throws exception 

});thread t2 = new thread(new runnable()

});t1.start();

t2.start();

thread.sleep(2000);

system.out.println(c.getcounter());

}

輸入結果:

enter add1

add1 sleep

enter add2

exit add2

add1 wake up

exit add1

多執行緒一些基礎筆記

thread.start 執行緒開啟 thread.sleep 100 模擬延時 thread.currentthread getname 當前執行緒 真實物件和 物件都要實現同乙個介面 物件要 真實角色 好處 物件可以做很多真實物件做不了得事情 真實物件專注做自己得事情 函式式介面的定義 labd...

C 多執行緒的一些理解

c 多執行緒程式設計有多種方法,傳統方法稍微繁瑣,不易理解,現給出一demo示例,說明執行同一任務達到並行執行的效果,從而提高程式效率。include include include opencv2 opencv.hpp using namespace std using namespace cv ...

對於多執行緒的一些理解

實現多執行緒的兩種方法 繼承thread類 實現runnable介面 jdk1.5之後提供了乙個心得callable介面 在啟動多執行緒的時候必須通過start 方法,而不能直接呼叫run 方法 原因 先來看下start 方法在thread類中的定義 public synchronized void...