iOS 建立多執行緒的三種方法

2021-09-02 15:18:52 字數 1418 閱讀 5390

(1)//通過nsobject的方法建立執行緒

//(這個方法會自動開闢乙個後台執行緒,引數1:在這個後台執行緒中執行的方法,引數2:用於傳遞引數)

[self performselectorinbackground:@selector(banzhuanplus) withobject:nil];

//第一步:建立執行緒

nsthread *thread = [[nsthread alloc] initwithtarget:self selector:@selector(banzhuanplus) object:nil];

//第二步:執行

[thread start];

[thread release];

(3)//nsoperation就是乙個操作單元,用來執行方法,是乙個抽象類,必須子類化或者使用系統建立好的子類(nsinvocationoperation or nsblockoperation)

// //nsoperation是最小的操作單元;只能夠執行一次;

// //nsinvocationoperation第一步:建立

nsinvocationoperation *invocation = [[nsinvocationoperation alloc] initwithtarget:self selector:@selector(banzhuanplus) object:nil];

// //第二步:(不設定的話不新增到佇列)在主線程中執行

// [invocation start];

//nsblockoperation第一步:建立

nsblockoperation *block = [nsblockoperation blockoperationwithblock:^];

// //第二步:執行(在主線程中執行)

// [block start];//如果新增到佇列就不要start了

// 這個佇列會自動幫咱們建立乙個輔助的執行緒

//這個佇列裡面只能夠新增nsoperation以及子類的物件;

nsoperationqueue *queue = [[nsoperationqueue alloc] init];

[queue setmaxconcurrentoperationcount:2];//設定最大並行數;

[queue addoperation:block];//只要把操作佇列新增到佇列中就會執行;

[queue addoperation:invocation];

//佇列: 先進先出

//棧: 先進後出

//佇列中涉及到序列和並行

//序列: 一次只能執行乙個任務

//並行: 一次可以執行多個任務

(整片複製的時候,注意沒有注釋的屬於一體) 

Java建立執行緒Thread的三種方法

1.通過繼承thread類建立執行緒 1 繼承thread類,重寫run 方法 2 建立繼承了thread類的類的物件,呼叫物件的start方法開啟執行緒 2.通過實現runnable介面建立執行緒 1 實現runnable介面,重寫run 方法 2 建立實現了runnable介面的類的物件,將物件...

建立執行緒的三種方法詳細對比

1 繼承thread類 步驟 定義類繼承thread 複寫thread類中的run方法 目的 將自定義 儲存在run方法,讓執行緒執行 呼叫執行緒的start方法 該方法有兩步 啟動執行緒,呼叫run方法。1 public class threaddemo1 15 16 17 繼承thread類 1...

iOS 建立多執行緒的幾種方法

nsthread 多執行緒方式1 例項方法 nsthread thread1 nsthread alloc initwithtarget self selector selector threadaction1 object nil 啟動執行緒 需要啟動執行緒 thread1 start 多執行緒方...