【iOS開發-多線程】使用NSThread建立多線程

來源:互聯網
上載者:User

標籤:多線程

線程的狀態

建立線程
//建立一個線程,回到用控制器裡面的run方法NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil]; //線程建立了,並沒有效果,需要啟動線程   [thread start];
獲得當前線程
NSThread *thread = [NSThread currentThread];
線程調度設定線程的優先順序

調度優先順序的取值範圍是0.0 ~ 1.0,預設0.5,值越大,優先順序越高

+ (double)threadPriority;+ (BOOL)setThreadPriority:(double)p;- (double)threadPriority;- (BOOL)setThreadPriority:(double)p;
其他建立線程的方式

優點:簡單快捷
缺點:無法對線程進行更詳細的設定

建立後自動啟動
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
隱式建立,在後台建立
[self performSelectorInBackground:@selector(run) withObject:nil];
讓線程阻塞,睡眠
+ (void)sleepUntilDate:(NSDate *)date;//開始睡眠,知道什麼日期回來+ (void)sleepForTimeInterval:(NSTimeInterval)ti;//睡多久
線程死亡
+ (void)exit;
線程同步
@synchronized(鎖對象) {     // 需要鎖定的代碼   }
線程間的通訊

一個線程執行的結果可以傳給另一個線程執行

/*傳遞給主線程*/- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;/*傳給自訂線程*/- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;

【iOS開發-多線程】使用NSThread建立多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.